gpt4 book ai didi

Python Pandas : drop columns from multi-indexed dataframe. 列已删除,但列名保留

转载 作者:行者123 更新时间:2023-11-28 21:42:06 27 4
gpt4 key购买 nike

我正在尝试创建多索引数据框的 View 。我想知道为什么列名在列被删除后仍然存在。

import panda as pd

df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6, 7, 8],
'x': [2, 2, 2, 2, 12, 12, 12, 12],
'y': [5.91, 4.43, 5.22, 1.31, 6.32, 6.78, 4.65, 1.98],
'z': [18.61, 17.60, 18.27, 16.18, 16.81, 16.37, 67.07, 46.00]})

pivot_df = df.pivot_table(index=['id'],columns=['x'],values=['y','z'])

[output]
>>> pivot_df
y z
x 2 12 2 12
id
1 5.91 NaN 18.61 NaN
2 4.43 NaN 17.60 NaN
3 5.22 NaN 18.27 NaN
4 1.31 NaN 16.18 NaN
5 NaN 6.32 NaN 16.81
6 NaN 6.78 NaN 16.37
7 NaN 4.65 NaN 67.07
8 NaN 1.98 NaN 46.00

>>> pivot_df.columns
MultiIndex(levels=[['y', 'z'], [2, 12]],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
names=[None, 'x'])

在上面的代码中,我可以在预期的级别 0 看到 ['y', 'z']。现在,我尝试删除“z”下的列。

new_pivot_df = pivot_df.drop('z',axis=1,level=0)

[output]
>>> new_pivot_df
y
x 2 12
id
1 5.91 NaN
2 4.43 NaN
3 5.22 NaN
4 1.31 NaN
5 NaN 6.32
6 NaN 6.78
7 NaN 4.65
8 NaN 1.98

>>> new_pivot_df.columns
MultiIndex(levels=[['y', 'z'], [2, 12]],
labels=[[0, 0], [0, 1]],
names=[None, 'x'])

在上面的代码中,new_pivot_df 表明“z”被删除了。但是,当我检查 new_pivot_df.columns 时,我仍然在列名中看到“z”。我想了解为什么会这样,我正在寻找一个优雅的建议来从多索引数据框中删除列(数据和名称)。

提前谢谢你。

最佳答案

版本 0.20.1 中的新功能 remove_unused_levels() :

new_pivot_df.columns = new_pivot_df.columns.remove_unused_levels()
new_pivot_df.columns

输出:

MultiIndex(levels=[['y'], [2, 12]],
labels=[[0, 0], [0, 1]],
names=[None, 'x'])

关于Python Pandas : drop columns from multi-indexed dataframe. 列已删除,但列名保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44120692/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com