向现有数据透视表添加行

问题描述 投票:0回答:2

我有以下数据透视表:

  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

有人对如何做到这一点有快速简单的建议吗?

python pandas pivot-table
2个回答
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)

0
投票

我想确保我们有相同的表结构,所以如果输出为:

your_pivot_table.loc[('Z', 100)]

apple   NaN
Orange  NaN
banana  1.3
Name: (Z, 100), dtype: float64

然后,解决方案是创建一个与上面的输出具有相同索引但具有不同值的系列。

我们需要一个值为 [3.5, 1.2, 2] 但具有相同索引的系列,而不是 [NaN, NaN, 1.3],这是我生成该系列的代码:

pd.Series([3.5, 1.2, 2], index = ['apple', 'orange', 'banana'])

它的输出是:

apple   3.5
Orange  1.3
banana  2
dtype: float64

最后一步是使用

.loc
将该系列插入数据透视表,因此我们将使用索引
your_pivot_table
将其插入到
('Price', '')
,因此插入所需行的最终代码如下所示:

your_pivot_table.loc[('Price', '')] = pd.Series([3.5, 1.2, 2], index = ['apple', 'orange', 'banana'])
© www.soinside.com 2019 - 2024. All rights reserved.