在数据透视表中-如何在列中(除了维度行之外)添加维度?

时间:2019-06-13 12:25:07

标签: python pandas

我有一个简单的数据集,我想在行中有2维。 还有列中的尺寸。

我有一个常规的数据透视表,我想将一个维度(周)作为列侧的维度(在所有指标之上),所以我将有两个指标(成本,安装量)周。

/ * agg表* /

df2Group = df2.groupby(['os','Campaign ID','week']).agg({'cost_plus_fee':'sum', 'installs':'sum'})

1 个答案:

答案 0 :(得分:0)

rename第一级别的MultiIndexDataFrame.unstackDataFrame.swaplevelDataFrame.sort_index一起使用:

df2 = pd.DataFrame({
        'os':['andriod'] * 10,
         'Campaign ID':[103292] * 5 +[103293] * 5,
         'week':[22,23,24] * 3 + [22],
         'cost_plus_fee':[1,3,5,7,1,0,4,5,6,3],
         'installs':[5,3,6,9,2,4,2,5,8,4]
})
print (df2)
        os  Campaign ID  week  cost_plus_fee  installs
0  andriod       103292    22              1         5
1  andriod       103292    23              3         3
2  andriod       103292    24              5         6
3  andriod       103292    22              7         9
4  andriod       103292    23              1         2
5  andriod       103293    24              0         4
6  andriod       103293    22              4         2
7  andriod       103293    23              5         5
8  andriod       103293    24              6         8
9  andriod       103293    22              3         4

df2Group = (df2.groupby(['os','Campaign ID','week'])
               .agg({'cost_plus_fee':'sum', 'installs':'sum'})
               .unstack()
               .swaplevel(1,0, axis=1)  
               .sort_index(axis=1, level=0)
               .rename(columns = lambda x: f'week {x}', level=0))
print (df2Group)
  week                      week 22                week 23           \
                    cost_plus_fee installs cost_plus_fee installs   
os      Campaign ID                                                 
andriod 103292                  8       14             4        5   
        103293                  7        6             5        5   

week                      week 24           
                    cost_plus_fee installs  
os      Campaign ID                         
andriod 103292                  5        6  
        103293                  6       12