如何检查 DataFrame 列中列表中的值并按条件插入值?

How to check values from list in DataFrame column and insert value by condition?

例如,我有下一个列表:

l = ['a', 'x', 't']

和数据框:

a = [{'sufix': 'a', 'qty': 5}, {'sufix': 'b', 'qty': 2}, {'sufix': 'c', 'qty': 7}, {'sufix': 'x', 'qty': 9}, {'sufix': 't', 'qty': 4}, {'sufix': 'p', 'qty': 1}]
df = pd.DataFrame(a)
print(df)

我需要什么,如果列表中的值 -> l 在列 df['sufix'] -> 创建新列 df['yes'] 并从列 df['qty'] 中输入值,否则df['yes'] = 0

我需要下一个结果:

from tokenize import String
import pandas as pd
import numpy as np
l = ['a', 'x', 't']
a = [{'sufix': 'a', 'qty': 5}, {'sufix': 'b', 'qty': "ww"}, {'sufix': 'c', 'qty': "a"}, {'sufix': 'x', 'qty': "9"}, {'sufix': 't', 'qty': 4}, {'sufix': 'p', 'qty': 1}]
df = pd.DataFrame(a).assign(yes=lambda x: np.where(x["qty"].isin(l), x["qty"],0))

还要处理文本。

如果我没理解错的话,大概是这样的:

df['yes'] = df['qty'][df['sufix'].isin(l)]
df['yes'] = df['yes'].fillna(0)

就像这样:

df['yes'] = df.sufix.isin(l) * df.qty

isin()sufix 列返回的布尔值将转换为 0 表示 False,1 表示 True,并乘以 qty 中的值。

输出:

  sufix  qty  yes
0     a    5    5
1     b    2    0
2     c    7    0
3     x    9    9
4     t    4    4
5     p    1    0