首页 > 解决方案 > 将列 wrt 中的 NULL 或 NA 替换为 pandas 数据框中的其他列

问题描述

我有一张桌子:

        df = pd.DataFrame([[0.1, 2, 55, 0,np.nan],
               [0.2, 4, np.nan, 1,99],
               [0.6, np.nan, 22, 5,88],
               [1.4, np.nan, np.nan, 4,77]],
               columns=list('ABCDE'))

    A    B     C  D     E
0  0.1  2.0  55.0  0   NaN
1  0.2  NaN   NaN  1  99.0
2  0.6  NaN  22.0  5  88.0
3  1.4  NaN   NaN  4  77.0

我想根据 A 列的条件替换 B 列中的 NaN 值。示例:

When  B is NULL and value in `column A > 0.2 and < 0.6` replace "NaN" in column B as 5
When B is NULL value in `column A > 0.6 and < 2` replace "NaN" in column B as 10

我试过这样的事情:

   if df["A"]>=val1 and pd.isnull(df['B']):
       df["B"]=5
  elif df["A"]>=val2 and df["A"]<val3 and pd.isnull(df['B']):
       df["B"]=10
  elif df["A"]<val4 and pd.isnull(df['B']):
       df["B"]=15

上面的代码不起作用。

请让我知道是否有任何其他替代方法使用 for 循环或应用函数来迭代 pandas 数据帧。

标签: python-3.xpandas

解决方案


您可以使用掩码:

df['B'] = df['B'].mask((df['A']>0.2) & (df['A']<0.6), df['B'].fillna(5))
df['B'] = df['B'].mask((df['A']>0.6) & (df['A']<2), df['B'].fillna(10))

或者您可以尝试 np.where 但我猜它会涉及很长的条件。


推荐阅读