为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蝴蝶刀刀 2021-05-30 00:07:01
我有以下数据框:列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]


查看完整回答
反对 回复 2021-06-01
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

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

a = a.iloc[:, 1:]


查看完整回答
反对 回复 2021-06-01
  • 2 回答
  • 0 关注
  • 169 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信