pandas DataFrame按多列值重新整形

时间:2016-12-10 17:00:05

标签: python pandas

我试图让自己摆脱JMP进行数据分析,但无法确定相当于JMP Split Columns功能的大熊猫。我从以下DataFrame开始:

In [1]: df = pd.DataFrame({'Level0': [0,0,0,0,0,0,1,1,1,1,1,1], 'Level1': [0,1,0,1,0,1,0,1,0,1,0,1], 'Vals': [1,3,2,4,1,6,7,5,3,3,2,8]})
In [2]: df
Out[2]:
    Level0  Level1  Vals
0        0       0     1
1        0       1     3
2        0       0     2
3        0       1     4
4        0       0     1
5        0       1     6
6        1       0     7
7        1       1     5
8        1       0     3
9        1       1     3
10       1       0     2
11       1       1     8

我可以使用pivot_table函数处理JMP函数的某些输出方案,但我很难理解Vals列被唯一组合拆分的情况Level0Level1提供以下输出:

Level0   0       1
Level1   0   1   0   1
0        1   3   7   5
1        2   4   3   3
2        1   6   2   8

我尝试了pd.pivot_table(df, values='Vals', columns=['Level0', 'Level1']),但这给出了不同组合的平均值:

Level0  Level1
0       0         1.333333
        1         4.333333
1       0         4.000000
        1         5.333333

我还尝试了pd.pivot_table(df, values='Vals', index=df.index, columns=['Level0', 'Level1'],它获取了我想要的列标题但不起作用,因为它强制输出与原始行具有相同的行数,因此输出有很多{{ 1}}值:

NaN

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

这是一个解决方法,但你可以这样做:

df.pivot_table(index=df.groupby(['Level0', 'Level1']).cumcount(), 
               columns=['Level0', 'Level1'], values='Vals', aggfunc='first')
Out: 
Level0  0     1   
Level1  0  1  0  1
0       1  3  7  5
1       2  4  3  3
2       1  6  2  8

这里的想法是原始DataFrame中的输出索引不容易获得。你可以通过以下方式获得它:

df.groupby(['Level0', 'Level1']).cumcount()
Out: 
0     0
1     0
2     1
3     1
4     2
5     2
6     0
7     0
8     1
9     1
10    2
11    2
dtype: int64

现在,如果您将此作为pivot_table的索引传递,则任意aggfunc(均值,最小值,最大值,第一个或最后一个)应该适合您,因为这些索引列对只有一个条目。