gpt4 book ai didi

python - Pandas 数据框在枢轴后 reshape

转载 作者:行者123 更新时间:2023-11-28 22:35:22 26 4
gpt4 key购买 nike

枢轴代码:

result = pandas.pivot_table(result, values=['value'], index=['index'], columns=['columns'], fill_value=0)

结果:

        value   value   value   
columns col1 col2 col3
index
idx1 14 1 1
idx2 2 0 1
idx3 6 0 0

我试过:

result.columns = result.columns.get_level_values(1)

然后我得到了这个:

columns col1    col2    col3
index
idx1 14 1 1
idx2 2 0 1
idx3 6 0 0

其实我想要的是这个:

index   col1    col2    col3
idx1 14 1 1
idx2 2 0 1
idx3 6 0 0

有什么办法可以实现吗?真的很感激帮助。提前谢谢你。

最佳答案

您需要通过 rename_axis 删除索引名称 (pandas 0.18.0 中的新功能):

df = df.rename_axis(None)

如果还需要删除列名,使用:

df = df.rename_axis(None, axis=1)

如果使用旧版本的 pandas,请使用:

df.columns.name = None
df.index.name = None

示例(如果从 pivot_table 中删除 [],则从列中删除 Multiindex):

print (result)
index columns value
0 1 Toys 5
1 2 Toys 6
2 2 Cars 7
3 1 Toys 2
4 1 Cars 9

print (pd.pivot_table(result, index='index',columns='columns',values='value', fill_value=0)
.rename_axis(None)
.rename_axis(None, axis=1))

Cars Toys
1 9 3.5
2 7 6.0

如果使用[],得到:

result = pd.pivot_table(result, values=['value'], index=['index'], columns=['columns'], fill_value=0)
.rename_axis(None)
.rename_axis((None,None), axis=1)
print (result)
value
Cars Toys
1 9 3.5
2 7 6.0

关于python - Pandas 数据框在枢轴后 reshape ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38240407/

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