我有以下数据:

列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时生成的空列索引?
发布于 2018-08-22 20:22:31
相反,您需要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列,因为您在文件名中捕获了它的值。
下面是一个使用groupby()的更有效的解决方案
grouped = racimitos.groupby('numeroLote')[['peso','fecha']]
[grouped.get_group(key).to_csv('racimitos{}.csv'.format(key), index=False) for key, item in grouped]发布于 2018-08-22 20:17:27
您可以选择从索引1开始的所有列,而不是尝试删除该未命名的列。
a = a.iloc[:, 1:]https://stackoverflow.com/questions/51974298
复制相似问题