Python 使用for循环和pd.dataframe相乘列
我很难创建一个新的数据表来显示年度能源使用数据。基本上,我想用不同的因子乘以能量来显示每年的能量消耗。 代码如下Python 使用for循环和pd.dataframe相乘列,python,pandas,dataframe,for-loop,Python,Pandas,Dataframe,For Loop,我很难创建一个新的数据表来显示年度能源使用数据。基本上,我想用不同的因子乘以能量来显示每年的能量消耗。 代码如下 #calculate energy amounts energy_use_by_fuel = pd.DataFrame() for hhid in energy_data.hhid.unique(): tempdtf = pd.DataFrame({ 'hhid':hhid, 'monthly_electricity': energy_dat
#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)
如你们所见,我想计算电力、煤气和木炭的不同能源使用。但是当我将数据乘以数字时,得到的数据帧能量是空的。函数df.append返回一个添加数据帧的新对象,因此我认为您的代码设置了错误的变量
#join
energy_use_by_fuel = energy_use_by_fuel.append(tempdtf, ignore_index = True)
欢迎来到堆栈溢出!您能否将能源数据中的特定数据以及预期输出编辑到您的问题中?这将帮助其他人解决此问题。代码仍然不起作用:。如果你认为有一个更简单的方法来做这件事使用其他pythonic方法,请让我知道!我愿意不使用循环。