如何在Pandas中重塑或转动DataFrame

时间:2014-06-22 16:15:39

标签: python pandas

我想在Pandas中重塑一个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

我想重塑一下:

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')

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

1 个答案:

答案 0 :(得分:4)

你可以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)