我有以下数据框:列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)然后,我得到类似于以下内容的数据集:会产生一个额外的列,就像上面红色框内所包围的一样……我尝试通过以下方式删除此列: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?
2 回答
呼如林
TA贡献1798条经验 获得超3个赞
你反而想要index=False,像这样:
for i in range(5,26):
a = racimitos[racimitos['numeroLote']==i][['peso','fecha','numeroLote']]
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]
添加回答
举报
0/150
提交
取消