gpt4 book ai didi

python - 根据条件在数据框 Pandas 中创建一列

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:54 25 4
gpt4 key购买 nike

我有两个列表

A = ['a','b','c','d','e']
B = ['c','e']

带列的数据框

      A
0 a
1 b
2 c
3 d
4 e

我希望为 B 中的元素与 A 匹配的行创建一个附加列。

      A  M
0 a
1 b
2 c match
3 d
4 e match

最佳答案

您可以使用 locnumpy.where和条件 isin :

df.loc[df.A.isin(B), 'M'] = 'match'
print (df)
A M
0 a NaN
1 b NaN
2 c match
3 d NaN
4 e match

或者:

df['M'] = np.where(df.A.isin(B),'match','')
print (df)

A M
0 a
1 b
2 c match
3 d
4 e match

关于python - 根据条件在数据框 Pandas 中创建一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43672958/

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