gpt4 book ai didi

python - 如何在 Pandas 中 reshape 或旋转 DataFrame

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

我想在 Pandas 中 reshape DataFrame 但不确定如何去做。以下是我的开头:

Phase Weight Value  CF
AA heavy 0.28 1.0
AB light 3.26 1.0
BX med 0.77 1.0
XY x light -0.01 1.0
AA heavy 0.49 1.5
AB light 5.10 1.5
BX med 2.16 1.5
XY x light 0.98 1.5
AA heavy 2.48 2.0
AB light 11.70 2.0
BX med 5.81 2.0
XY x light 3.46 2.0

我想 reshape 成这样:

Phase       Weight  1.0     1.5     2.0
AA heavy 0.28 0.49 2.48
AB light 3.26 5.10 11.70
BX med 0.77 2.16 5.81
XY x light -0.01 0.98 3.46

因此列名现在是 CF 中的值,新表中行和列的交集是原始表中值列中的值。

我知道我可以像这样将 Phase 列用作索引:

df.pivot(index='Phase', columns='CF', values='Value)

但后来我错过了重量列。我试过了,但出现错误

df.pivot(index='Phase', columns=['Weight','CF'], values='Value')

有没有办法用一条语句做到这一点?如果没有,最好的方法是什么?

最佳答案

您可以 pd.pivot_table 将多个名称作为索引/列参数的参数。我还认为您希望索引上的权重(使其成为输出中的一列)而不是列上的权重(它将不同的值转换为列)。

In [27]: df.pivot_table(index=['Phase','Weight'], columns='CF', values='Value').reset_index()
Out[27]:
CF Phase Weight 1.0 1.5 2.0
0 AA heavy 0.28 0.49 2.48
1 AB light 3.26 5.10 11.70
2 BX med 0.77 2.16 5.81
3 XY x light -0.01 0.98 3.46

编辑:

关于你的另一个问题,DataFrame 的 .columns 是一个索引(就像在行上一样),并且除了实际值之外还有一个 .name .据我所知,它通常仅用于显示目的。

In [74]: df.columns
Out[74]: Index([u'Phase', u'Weight', 1.0, 1.5, 2.0], dtype='object')

In [75]: df.columns.name
Out[75]: 'CF'

In [76]: df.columns.values
Out[76]: array(['Phase', 'Weight', 1.0, 1.5, 2.0], dtype=object)

关于python - 如何在 Pandas 中 reshape 或旋转 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24353147/

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