猿问

删除空索引列熊猫数据框 - 标签 [' '] 未包含在轴中

我有以下数据框:

列numeroLote的范围之间5,以25值。我想csv在numeroLote更改它们的值时为每个数据创建一个导出文件,我执行以下操作:


for i in range(5,26):

    print(i)

    a = racimitos[racimitos['numeroLote']==i][['peso','fecha','numeroLote']]

    a.to_csv('racimitos{}.csv'.format(i), sep=',', header=True, index=True)

然后,我得到类似于以下内容的数据集:

http://img4.mukewang.com/60b5f6150001bfbe04340408.jpg

会产生一个额外的列,就像上面红色框内所包围的一样……


我尝试通过以下方式删除此列:


for i in range(5,26):

    print(i)

    a = racimitos[racimitos['numeroLote']==i][['peso','fecha','numeroLote']]

    a.to_csv('racimitos{}.csv'.format(i), sep=',', header=True, index=True)

    a.drop(columns=[' '], axis=1,)

但是我得到这个错误:


KeyError                                  Traceback (most recent call last)

<ipython-input-18-e3ad718d5396> in <module>()

      9     a = racimitos[racimitos['numeroLote']==i][['peso','fecha','numeroLote']]

     10     a.to_csv('racimitos{}.csv'.format(i), sep=',', header=True, index=True)

---> 11     a.drop(columns=[' '], axis=1,)


~/anaconda3/envs/sioma/lib/python3.6/site-packages/pandas/core/indexes/base.py in drop(self, labels, errors)

   4385             if errors != 'ignore':

   4386                 raise KeyError(

-> 4387                     'labels %s not contained in axis' % labels[mask])

   4388             indexer = indexer[~mask]

   4389         return self.delete(indexer)


KeyError: "labels [' '] not contained in axis"

如何删除执行导出时生成的这个空列索引to.csv?


蝴蝶刀刀
浏览 170回答 2
2回答

呼如林

你反而想要index=False,像这样:for i in range(5,26):&nbsp; &nbsp; a = racimitos[racimitos['numeroLote']==i][['peso','fecha','numeroLote']]&nbsp; &nbsp; a.to_csv('racimitos{}.csv'.format(i), sep=',', header=True, index=False)顺便说一句,我认为numeroLote在打印到 .csv 文件时没有必要包含该列,仅仅因为您在文件名中捕获了它的值。这是IMO使用groupby()以下更有效的解决方案:grouped = racimitos.groupby('numeroLote')[['peso','fecha']][grouped.get_group(key).to_csv('racimitos{}.csv'.format(key), index=False) for key, item in grouped]

小唯快跑啊

您可以选择从索引1开始的所有列,而不必尝试删除该未命名的列。a&nbsp;=&nbsp;a.iloc[:,&nbsp;1:]
随时随地看视频慕课网APP

相关分类

Python
我要回答