如果另一列中的相应值也为 NaN,则将一列中的所有值设置为 NaN

Set all values in one column to NaN if the corresponding values in another column are also NaN

目标是通过将一列中的所有值设置为 NaN 来维护两列之间的关系。

具有以下数据框:

df = pd.DataFrame({'a': [np.nan, 2, np.nan, 4],'b': [11, 12 , 13, 14]})

     a   b
0  NaN  11
1    2  12
2  NaN  13
3    4  14

维护从列 a 到列 b 的关系,其中更新所有 NaN 值导致:

     a    b
0  NaN  NaN
1    2   12
2  NaN  NaN
3    4   14

实现所需行为的一种方法是:

df.b.where(~df.a.isnull(), np.nan)

有没有其他方法可以维系这样的关系?

您可以在 NaN 行上使用 mask

In [366]: df.mask(df.a.isnull())
Out[366]:
     a     b
0  NaN   NaN
1  2.0  12.0
2  NaN   NaN
3  4.0  14.0

对于跨列的任何 NaN 使用 df.mask(df.isnull().any(1))

dropnareindex

结合使用
df.dropna().reindex(df.index)
Out[151]: 
     a     b
0  NaN   NaN
1  2.0  12.0
2  NaN   NaN
3  4.0  14.0

另一个是:

df.loc[df.a.isnull(), 'b'] = df.a

不是更短,而是够用。

使用 pd.Series.notnull 避免取布尔级数的负数:

df.b.where(df.a.notnull(), np.nan)

但是,实际上,您现有的解决方案没有任何问题。

使用np.where(),

df['b'] = np.where(df.a.isnull(), df.a, df.b)

工作 - np.where(条件,[a, b])

Return 个元素,来自 ab,取决于 condition.

输出:

>>> df
    a       b
0   NaN     NaN
1   2.0     12.0
2   NaN     NaN
3   4.0     14.0