【发布时间】: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
请注意,我需要以掩蔽方式进行,但有多种方法可以实现这一点
【问题讨论】: