【问题标题】:Pandas masking the column replaces previous non matched value to NaN屏蔽该列的 Pandas 将以前的非匹配值替换为 NaN
【发布时间】:2022-07-06 15:48:50
【问题描述】:

假设我有一个数据框

d = {
    "cid": [1, 3, 3],
    "txt": ["Kakashi is GOAT", "Eleven is El", "Hello agian"],
     "anime": ['Kakashi ', 'el', 'mouse']
}

df = pd.DataFrame(data=d)
df['code'] = df['anime'].astype('category').cat.codes

我需要创建一个新列code,如果 txt 中存在动画,则该列将包含代码中的值,否则为 999

这是我的面具

mask = df.apply(lambda x: x.anime.lower() in x.txt.lower(), axis=1)
df['newCol'] = 999
df['newCol'] = df.loc[mask, 'code']

但这给了我浮点值,并将 999 替换为 NaN

输出:

df
   cid              txt     anime  code  newCol
0    1  Kakashi is GOAT  Kakashi      0     0.0
1    3     Eleven is El        el     1     1.0
2    3      Hello agian     mouse     2     NaN

预期:

df
   cid              txt     anime    code  newCol
0    1  Kakashi is GOAT    Kakashi      0     0
1    3     Eleven is El      el         1     1
2    3      Nothing         mouse       2     999

请注意,我需要以掩蔽方式进行,但有多种方法可以实现这一点

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以跳过 mask 步骤,只需使用(几乎)相同的 lambda 函数分配 newCol 值:

    df['newCol'] = df.apply(lambda x: x.code if x.anime.lower() in x.txt.lower() else 999, axis=1)
    

    输出:

       cid              txt     anime  code  newCol
    0    1  Kakashi is GOAT  Kakashi      0       0
    1    3     Eleven is El        el     1       1
    2    3      Hello agian     mouse     2     999
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 2016-10-23
      • 2017-08-25
      相关资源
      最近更新 更多