将3列(x,y,结果)Python Pandas DataFrame转换为结果值的DataFrame,其中x(唯一)为行,y(唯一)为列

时间:2014-07-26 10:47:24

标签: python numpy pandas dataframe

我想转换Python Pandas DataFrame df,如:

      x  y  result
id                
1  -0.8 -1    0.64
2  -0.8  0   -0.36
3  -0.4 -1    0.16
4  -0.4  0   -0.84
5   0.0 -1    0.00
6   0.0  0   -1.00
7   0.4 -1    0.16
8   0.4  0   -0.84
9   0.8 -1    0.64
10  0.8  0   -0.36

到这样的DataFrame:

        -1     0
-0.8  0.64 -0.36
-0.4  0.16 -0.84
 0.0     0 -1.00
 0.4  0.16 -0.84
 0.8  0.64 -0.36

我知道如何获得唯一的x值:

df["x"].unique()

和唯一的y值:

df["y"].unique()

但我不知道如何在DataFrame中“分发”result列值。

我更喜欢矢量化解决方案以避免循环。

1 个答案:

答案 0 :(得分:3)

这是 pivot 操作,您可以使用.pivot_table

>>> df.pivot_table(values='result', index='x', columns='y')
y       -1     0
x               
-0.8  0.64 -0.36
-0.4  0.16 -0.84
 0.0  0.00 -1.00
 0.4  0.16 -0.84
 0.8  0.64 -0.36

.pivot

>>> df.pivot(index='x', columns='y')['result']
y       -1     0
x               
-0.8  0.64 -0.36
-0.4  0.16 -0.84
 0.0  0.00 -1.00
 0.4  0.16 -0.84
 0.8  0.64 -0.36

.groupby后跟.unstack

>>> df.groupby(['x', 'y'])['result'].aggregate('first').unstack()
y       -1     0
x               
-0.8  0.64 -0.36
-0.4  0.16 -0.84
 0.0  0.00 -1.00
 0.4  0.16 -0.84
 0.8  0.64 -0.36