python - 如何有条件地转换熊猫数据框列
问题描述
我有 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)
解决方案
你应该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
推荐阅读
- google-cast - 如何隐藏或更改下一个队列项目的倒计时外观?
- electron - 无法在 Windows 10 上使用 ffi 运行电子重建 (src\ffi.cc(228): error C2065: 'Handle': undeclared identifier)
- html - 根据组件值在角度组件之间画线的最佳做法是什么?
- excel - 如何在 VBA 中将 If 语句变成 For 循环
- python - 如何使用python从下拉列表中提取数据
- r - 比较数据帧中的单词并计算每个对的最大单词长度的矩阵
- regex - Ansible 正则表达式匹配字符串并提取行
- java - JDK 9.0.4 和 Derby 10.14.2 找不到创建的表
- angular - i18n 关于 Angular 7 中具有复数/选择的属性
- tfs - 如何启动由 TFS Release Agent 执行后不关闭的控制台程序