首页 > 解决方案 > 如何有条件地转换熊猫数据框列

问题描述

我有 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)

标签: pythonpython-3.xpandasdataframefor-loop

解决方案


你应该np.select在这里使用:

import numpy as np

df2["Volume_hedge"] = np.select(
    [df2["Unit_hedge"].eq("Thousands of Barrels per Day")], 
    [df2["Volume_hedge"].div(1000)], 
    df2["Volume_hedge"]
)

这会将Unit_hedge等于“每天千桶”的所有行除以 1000,并让所有其他行保持不变。

这还具有不迭代完成的优点,使用时更快,pandas并且numpy


推荐阅读