正在删除axis中不包含的空索引列pandas dataframe labels['']

2024-10-02 04:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

enter image description here

numerote介于525之间。 我想在numerote更改数值并执行以下操作时,为每个数据创建一个导出csv文件:

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)

然后,我得到的数据集类似于:

enter image description here

会生成一个附加的列,就像上面红色框中的列一样

我尝试用以下方法删除此列:

^{pr2}$

但我得到一个错误:

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时生成的空列索引?在


Tags: csvto数据intrueformatlabelskeyerror
2条回答

相反,您需要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)

另外,我认为在打印到.csv文件时没有必要包含numeroLote列,因为您在文件名中捕获了它的值。在

以下是IMO使用groupby()更有效的解决方案:

^{pr2}$

您可以选择从索引1开始的所有列,而不是尝试删除未命名的列。在

a = a.iloc[:, 1:]

相关问题 更多 >

    热门问题