gpt4 book ai didi

python - 如何在系列的多个条件下将值设置为 np.nan?

转载 作者:行者123 更新时间:2023-12-03 16:31:10 25 4
gpt4 key购买 nike

假设我有一个数据框:

    A   B   C   D   E   F
0 x R i R nan h
1 z g j x a nan
2 z h nan y nan nan
3 x g nan nan nan nan
4 x x h x s f
我想替换所有单元格:
  • 第 0 行的值是 R ( df.loc[0] == 'R' )
  • 单元格不是 'x' ( != 'x' )
  • 仅第 2 行及以下 (2:)

  • np.nan .
    基本上我想做:
    df.loc[2:,df.loc[0]=='R']!='x' = np.nan
    我收到错误:
    SyntaxError: can't assign to comparison
    我只是不知道语法应该如何。
    我试过了
    df[df.loc[2:,df.loc[0]=='R']!='x']
    但这并没有列出我想要的值。

    最佳答案

    解决方案

    mask = df.ne('x') & df.iloc[0].eq('R')
    mask.iloc[:2] = False

    df.mask(mask)

    A B C D E F
    0 x R i R NaN h
    1 z g j x a NaN
    2 z NaN NaN NaN NaN NaN
    3 x NaN NaN NaN NaN NaN
    4 x x h x s f
    解释
    建立面具
  • df.ne('x')
            A      B     C      D     E     F
    0 False True True True True True
    1 True True True False True True
    2 True True True True True True
    3 False True True True True True
    4 False False True False True True
  • 但我们希望与 df.iloc[0].eq('R') 一起使用这是一个 Series .事实证明,如果我们只是 &这两个放在一起,它将对齐 Series使用步骤 1 中掩码的列进行索引。
     A    False
    B True
    C False
    D True
    E False
    F False
    Name: 0, dtype: bool

    # &

    A B C D E F
    0 False True True True True True
    1 True True True False True True
    2 True True True True True True
    3 False True True True True True
    4 False False True False True True

    # GIVES YOU

    A B C D E F
    0 False True False True False False
    1 False True False False False False
    2 False True False True False False
    3 False True False True False False
    4 False False False False False False
  • 最后,我们想从这些恶作剧中排除前两行,所以......
     mask.iloc[:2] = False
  • 关于python - 如何在系列的多个条件下将值设置为 np.nan?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66803464/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com