Pandas DataFrame:更改列值?

luk*_*rku 3 python dataframe pandas

我有一个 df,其中两列值有TrueFalse或者NaN

df

            a         b           c

    0      a         True        NaN
    1      b         False       True
    2      c         NaN         False
    3      d         NaN         NaN
    4      e         False       NaN
    5      f         True        False
Run Code Online (Sandbox Code Playgroud)

我正在尝试将列bc.

如果True出现在一列中,另一列将是FalseIf NaNpresent change that False

对于False. 如果NaN在两列中都存在。将两个值更改为False

结果df:

            a         b           c

    0      a         True        False
    1      b         False       True
    2      c         True        False
    3      d         False       False
    4      e         False       True
    5      f         True        False
Run Code Online (Sandbox Code Playgroud)

Qua*_*ang 5

让我们尝试两步填充:

s = df[['b','c']]

# both are `NaN`, fill with `False`
df.loc[s.isna().all(1), ['b','c']] = False

# inverse the sum 
sums = (1 - s.sum(1)).astype(bool)

# fill the remaining `NaN` with the inverse sum
df[['b','c']] = s.apply(lambda x: x.fillna(sums))
Run Code Online (Sandbox Code Playgroud)

输出:

   a      b      c
0  a   True  False
1  b  False   True
2  c   True  False
3  d  False  False
4  e  False   True
5  f   True  False
Run Code Online (Sandbox Code Playgroud)