我要改NaN
一列中的值基于另一列的值。
第一个表
目标表格
所以我想将 NaN 更改为 0,如果该行中 A 列的值也是 0。
我创建的Python代码:
for i in range(len(df)):
if df.loc[i,'A'] == 0 and math.isnan(df.loc[i,'B']) = True:
df.loc[i,'B'] = 0
但是这段代码看起来很慢,因为我想对 2000 万行执行此操作。有没有更快的方法来做到这一点?
最佳答案
首先使用&
(逐元素and
运算符)组合条件:
conditions = df['B'].isnull() & df['A'].eq(0)
# 0 False
# 1 True
# 2 False
# 3 False
# dtype: bool
然后您可以向量化分配(无循环):
使用单个
loc
:df.loc[conditions, 'B'] = 0
或者
mask
满足这些条件的值为 0:df['B'] = df['B'].mask(conditions, 0)
输出:
# A B
# 0 2 3.0
# 1 0 0.0
# 2 2 NaN
# 3 4 2.0
关于python - 根据 pandas DataFrame 中其他列的值将 NaN 值更改为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69231243/