【问题标题】:multiplying columns using for-loop and pd.dataframe使用 for 循环和 pd.dataframe 将列相乘
【发布时间】:2019-08-23 01:48:58
【问题描述】:

我无法创建显示年度能源使用数据的新数据表。基本上,我想将能源乘以不同的因素来显示每年的能源使用量。
代码如下。

#calculate energy amounts

energy_use_by_fuel = pd.DataFrame()
for hhid in energy_data.hhid.unique(): 
    tempdtf = pd.DataFrame({
       'hhid':hhid, 
       'monthly_electricity': energy_data.loc[energy_data.hhid == hhid, 'estimated_kwh_monthly']*3, 
       'monthly_gas': energy_data.loc[energy_data.hhid == hhid, 'monthly_gas_use_kg'] * 4,
       'monthly_charcoal': energy_data.loc[energy_data.hhid == hhid, 
       'monthly_charcoal_use_kg'] * 5})

    #join
    tempdtf = energy_use_by_fuel.append(tempdtf, ignore_index = True)

如您所见,我想计算电力、天然气和木炭的不同能源用途。但是当我将数据乘以数字时,生成的数据框energy_use_by_fuel 为空。

【问题讨论】:

  • 欢迎来到 Stack Overflow!您能否编辑来自energy_data 的问题特定数据以及预期的输出?这将帮助其他人帮助解决问题。

标签: python pandas dataframe for-loop


【解决方案1】:

函数df.append() 确实返回了一个添加DataFrame 的新对象,所以我认为您的代码设置了错误的变量。

#join
energy_use_by_fuel = energy_use_by_fuel.append(tempdtf, ignore_index = True)

【讨论】:

  • 代码仍然无法工作 :(。如果您认为使用其他 pythonic 方法有更简单的方法,请告诉我!我愿意不使用循环。
猜你喜欢
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 2013-05-16
  • 2019-03-30
  • 1970-01-01
  • 2021-10-31
相关资源
最近更新 更多