将行添加到现有数据透视表

时间:2017-11-22 17:15:42

标签: python pandas pivot-table

我有以下数据透视表:

  Fruit |                 |  apple |   orange  |   banana  
 Market |   # num bracket |        |           |           
:-----------------------------------------------------------:    
 X      |   100           |   1.2  |   1.0     |     NaN     
 Y      |   50            |   2.0  |   3.5     |     NaN    
 Y      |   100           |   NaN  |   3.6     |     NaN    
 Z      |   50            |   NaN  |     NaN   |     1.6    
 Z      |   100           |   NaN  |     NaN   |     1.3

我想在底部的下一行添加

Fruit   |  apple |  orange  |   banana  
Price   |  3.5   | 1.2      |  2

所以新表格如下所示

 Fruit  |      x          |  apple |   orange  |   banana  
 Market |   # num bracket |        |           |           
:-----------------------------------------------------------:    
 X      |   100           |   1.2  |   1.0     |     NaN     
 Y      |   50            |   2.0  |   3.5     |     NaN    
 Y      |   100           |   NaN  |   3.6     |     NaN    
 Z      |   50            |   NaN  |     NaN   |     1.6    
 Z      |   100           |   NaN  |     NaN   |     1.3   
 Price  |                 |  3.5   | 1.2      |      2

是否有人可以快速轻松地推荐如何做到这一点?

2 个答案:

答案 0 :(得分:0)

temp_df = pd.DataFrame(data=[{'Fruit Market':'Price',
                              'apple':3.5,
                              'orange':1.2
                              'banana':2}],
                       columns=['Fruit Market','x','apple','orange','banana'])

pd.concat([df, temp_df], axis=0, ignore_index=True)

答案 1 :(得分:-1)

您需要在一行MultiIndexappend中创建DataFrame到第一个DataFrame:

如果第一列不是索引:

df1 = pd.DataFrame({'Fruit':['Price'], 'apple':[3.5], 'orange':[1.2], 'banana':[2]})
print (df1)
   Fruit  apple  banana  orange
0  Price    3.5       2     1.2

df11 = df1.assign(**{'# num bracket': ''}).set_index(['Fruit', '# num bracket'])
print (df11)
                     apple  banana  orange
Fruit # num bracket                       
Price                  3.5       2     1.2

如果df1中的第一列是index

df1 = pd.DataFrame({'apple':[3.5], 'orange':[1.2], 'banana':[2]}, index=['Price'])
df1.index.name = 'Fruit'
print (df1)
       apple  banana  orange
Fruit                       
Price    3.5       2     1.2


df11 = df1.assign(**{'# num bracket': ''}).set_index(['# num bracket'], append=True)
print (df11)
                     apple  banana  orange
Fruit # num bracket                       
Price                  3.5       2     1.2
df = df.append(df11)
print (df)
                      apple  banana  orange
Market # num bracket                       
X      100              1.2     NaN     1.0
Y      50               2.0     NaN     3.5
       100              NaN     NaN     3.6
Z      50               NaN     1.6     NaN
       100              NaN     1.3     NaN
Price                   3.5     2.0     1.2