如何在pandas dataframe中使用set_levels()在drop()之后?可能的错误?

2024-04-20 07:06:53 发布

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

我有一个复杂的多索引数据帧,我想更改一些列名。我使用set_levels()来实现这一点,它是有效的。你知道吗

但是,如果在使用set\u levels()函数之前,我使用drop()删除了一些不需要的列,那么set\u levels()会给我一个奇怪的错误。我已经尝试了一个基本的例子,在那里它的工作,所以我不知道什么是特别在我的具体数据帧。你知道吗

我尝试使用reindex()和copy()使用临时中间数据帧,但没有解决问题。你知道吗

这是已知的错误吗?你知道吗

以下是更详细的问题:

我的数据帧:

balanceData_a1b

dataframe (屏幕2100列中的not与2015列相同)

如果我使用set_levels()来更改第一列,它将正常工作:

balanceData_a1b.columns.set_levels([ [2015, 2100], ['changed_name','dt','rev','rt_in','rt_out','sa','st','avg_price']], inplace=True)

dataframe

相反,如果在运行set\u levels()之前,我删除了“rev”列,则会出现以下错误:

balanceData_a1b.drop([(2015,'rev')],axis=1, inplace=True) 
balanceData_a1b.drop([(2100,'rev')],axis=1, inplace=True)
balanceData_a1b

dataframe

balanceData_a1b.columns.set_levels([ [2015, 2100], ['changed_name','dt','rt_in','rt_out','sa','st','avg_price']], inplace=True)
# notice that compared to the first attempt I removed here the 'rev' column, as I dropped it

error

我注意到,当我删除列时,dataframe显示时没有“rev”删除的列,但columns属性仍然显示它们:

balanceData_a1b.columns 

enter image description here

这是预期的行为吗(例如,由于某些缓存?)如果是,如何更新列索引?你知道吗


Tags: columns数据nametrue错误dtrevdrop