pandas pivot_table Spaltennamen

Für einen dataframe, wie diese:

d = {'id': [1,1,1,2,2], 'Month':[1,2,3,1,3],'Value':[12,23,15,45,34], 'Cost':[124,214,1234,1324,234]}
df = pd.DataFrame(d)

     Cost  Month  Value  id  
0    124       1     12   1  
1    214       2     23   1  
2    1234      3     15   1  
3    1324      1     45   2  
4    234       3     34   2  

auf die ich mich bewerben pivot_table

df2 =    pd.pivot_table(df, 
                        values=['Value','Cost'],
                        index=['id'],
                        columns=['Month'],
                        aggfunc=np.sum,
                        fill_value=0)

bekommen df2:

       Cost            Value          
Month     1    2     3     1   2   3   
id                                  
1       124  214  1234    12  23  15
2      1324    0   234    45   0  34

gibt es eine einfache Möglichkeit, um format resultierenden dataframe Spalte Namen wie

id     Cost1    Cost2     Cost3 Value1   Value2   Value3   
1       124      214      1234    12        23       15
2      1324       0       234     45         0       34

Wenn ich das Tue:

df2.columns =[s1 + str(s2) for (s1,s2) in df2.columns.tolist()]

Bekomme ich:

    Cost1  Cost2  Cost3  Value1  Value2  Value3
id                                             
1     124    214   1234      12      23      15
2    1324      0    234      45       0      34

How, um loszuwerden, die extra-level?

Dank!

InformationsquelleAutor muon | 2015-10-22

Schreibe einen Kommentar