【问题标题】:How to add a new row by summing the two rows with different multiindex in pandas dataframe?如何通过将熊猫数据框中具有不同多索引的两行相加来添加新行?
【发布时间】:2021-11-25 02:50:17
【问题描述】:

我有一个 pandas 数据框,如下所示(注意:df.to_dict() 在问题末尾给出:

model   AIM/CGE 2.0 AIM/CGE 2.1 IMAGE 3.0.1
scenario    SSP1-19 SSP2-19 TERL_15D_LowCarbonTransportPolicy   TERL_15D_NoTransportPolicy  IMA15-LiStCh
module  variable                    
energy_investment_solar Investment|Energy Supply|Electricity|Solar  NaN NaN 7205.6445   8676.6235   0.0
energy_investment_wind  Investment|Energy Supply|Electricity|Wind   NaN NaN 11054.4915  11674.4485  0.0

有两个索引:module 和 variable。我想对两行求和并将其附加为新行。新行应该有索引energy_investment_vre。

我得到行的总和

sum = df.loc["energy_investment_solar"].values + df.loc["energy_investment_wind"].values

但是,我不能将其附加为新行。我试过了:

df.loc["energy_investment_vre"] = df.loc["energy_investment_solar"].values + df.loc["energy_investment_wind"].values

这给了我一个

ValueError: 无法设置列不匹配的行

我也试过了:

df.loc["energy_investment_vre","Investment|Energy Supply|Electricity|VRE"] = df.loc["energy_investment_solar"].values + df.loc["energy_investment_wind"].values

这给了我一个

IndexError: 只有整数、切片 (:)、省略号 (...)、 numpy.newaxis (None) 和整数或布尔数组是有效的索引

我也试过df.append([sum])这给了我一个

ValueError:必须通过二维输入。形状=(1, 1, 5)

将这两行之和作为一行的正确方法是什么?我也可以为新行设置一个新的变量名Investment|Energy Supply|Electricity|VRE 吗?

df.to_dict() looks as follows:
{('AIM/CGE 2.0',
  'SSP1-19'): {('energy_investment_solar',
   'Investment|Energy Supply|Electricity|Solar'): nan, ('energy_investment_wind',
   'Investment|Energy Supply|Electricity|Wind'): nan},
 ('AIM/CGE 2.0',
  'SSP2-19'): {('energy_investment_solar',
   'Investment|Energy Supply|Electricity|Solar'): nan, ('energy_investment_wind',
   'Investment|Energy Supply|Electricity|Wind'): nan},
 ('AIM/CGE 2.1',
  'TERL_15D_LowCarbonTransportPolicy'): {('energy_investment_solar',
   'Investment|Energy Supply|Electricity|Solar'): 7205.644499999999, ('energy_investment_wind',
   'Investment|Energy Supply|Electricity|Wind'): 11054.4915},
 ('AIM/CGE 2.1',
  'TERL_15D_NoTransportPolicy'): {('energy_investment_solar',
   'Investment|Energy Supply|Electricity|Solar'): 8676.6235, ('energy_investment_wind',
   'Investment|Energy Supply|Electricity|Wind'): 11674.448499999999},
 ('IMAGE 3.0.1',
  'IMA15-LiStCh'): {('energy_investment_solar',
   'Investment|Energy Supply|Electricity|Solar'): 0.0, ('energy_investment_wind',
   'Investment|Energy Supply|Electricity|Wind'): 0.0}}

【问题讨论】:

  • df.loc[("energy_investment_vre","Investment|Energy Supply|Electricity|VRE")] = df.sum()?
  • 它返回所有列的 NaN 值。

标签: python python-3.x pandas dataframe indexing


【解决方案1】:

为多索引以及所有列(使用 :) 指定元组,如下所示:

df.loc[('energy_investment_vre', 'Investment|Energy Supply|Electricity|VRE'),:] = df.sum()

【讨论】:

    猜你喜欢
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2018-07-17
    • 1970-01-01
    • 2019-02-24
    相关资源
    最近更新 更多