转置部分熊猫数据帧

时间:2014-02-17 18:56:33

标签: python pandas dataframe

我有以下数据框:

>>> df
Out[15]: 
      group   type  amount  number
0   group_A    buy     100     123
1   group_A   view       0     111
2   group_B   view       0     222
3   group_A   view       0     222 

我想转动数据,以便我最终得到:

              type  group_A   group_B
0    amount    buy      100         0
1    number    buy        0       123
2    number   view      333       222

我如何做到这一点?

1 个答案:

答案 0 :(得分:4)

使用:

df=pd.DataFrame([['group_A','buy',100,123],['group_A','view',0,111],['group_B','view',0,222],['group_A','view',0,222]],columns=['group','type','amount','number'])

首先对指数求和并定位:

>>> df = df.groupby(['type','group']).sum().transpose().stack(0).reset_index()
>>> df
group level_0  type  group_A  group_B
0      amount   buy      100      NaN
1      amount  view        0        0
2      number   buy      123      NaN
3      number  view      333      222

删除全部为零的行:

df = df[~((df['group_A']==0) | (df['group_B']==0))]

Fillna的:

>>> df.fillna(0)
group level_0  type  group_A  group_B
0      amount   buy      100        0
2      number   buy      123        0
3      number  view      333      222

在这里的一些地方有点猜测,但它应该给你一个开始。