【发布时间】:2020-01-15 16:29:41
【问题描述】:
我有 2 列要循环遍历,“Volume_hedge”和“Unit_hedge”。对于每一行,如果“Unit_hedge”中的数据显示“每天数千桶”,我想除以“Volume_hedge”中的数字(与“Unit_hedge”在同一行中,等于“每天数千桶” ") 乘以 1000。
我尝试遍历枚举的两个列和之后的 if 语句。就像我说的,我为前 2 行工作,但不为其余的。
df2 = DataFrame(x)
columns_to_select = ['Volume_hedge', 'Unit_hedge']
for i, row in enumerate(columns_to_select):
if df2['Unit_hedge'].loc[i] == 'Thousands of Barrels per Day':
new_row = df2['Volume_hedge'].loc[i] / 1000
else:
none
df2['Volume_hedge'].loc[i] = new_row
print(df2[columns_to_select].loc[0:8])
预期结果:
Volume_hedge Unit_hedge
0 0.03 Thousands of Barrels per Day
1 0.024 Thousands of Barrels per Day
2 0.024 Thousands of Barrels per Day
3 0.024 Thousands of Barrels per Day
4 0.024 Thousands of Barrels per Day
5 0.024 Thousands of Barrels per Day
6 0.024 Thousands of Barrels per Day
7 32850000 (MMBtu/Bbl)
8 4404000 (MMBtu/Bbl)
实际结果:
Volume_hedge Unit_hedge
0 0.03 Thousands of Barrels per Day
1 0.024 Thousands of Barrels per Day
2 24 Thousands of Barrels per Day
3 24 Thousands of Barrels per Day
4 24 Thousands of Barrels per Day
5 24 Thousands of Barrels per Day
6 24 Thousands of Barrels per Day
7 32850000 (MMBtu/Bbl)
8 4404000 (MMBtu/Bbl)
【问题讨论】:
-
请格式化您的代码。
标签: python python-3.x pandas dataframe for-loop