如何根据列列表值和附加列中的值添加pandas "匹配"?

问题描述 投票:0回答:2

我有一个数据框架,其中包含一个名为Multiple_IDS的标识符列表列和一个名为ID的列。现在,我想创建一个名为 "Match "的附加列,它可以告诉一个ID是否包含在Multiple_IDs列中。输出结果应该是一个名为Match的额外列,它包含True或False值。下面是一些输入数据的示例。

data = {'ID':[2128441, 2128447, 2128500], 'Multiple_IDs':["2128442, 2128443, 2128444, 2128441", "2128446, 2128447", "2128503, 2128508"]}
df = pd.DataFrame(data) 

列表的数据类型是 "对象"

根据上面提供的输入数据,希望的输出是这样的。

enter image description here

我知道我可以使用explode来实现这一点,然后比较这些值,但我想知道是否有更优雅的方法?

python pandas list conditional-statements matching
2个回答
1
投票

使用 "Multiple_IDS "和 "ID "列。in 语句如果可以测试,而不需要单独进行测试 ID:

df['Match'] = [str(x) in y for x, y in df[['ID','Multiple_IDs']].to_numpy()]
print (df)
        ID                        Multiple_IDs  Match
0  2128441  2128442, 2128443, 2128444, 2128441   True
1  2128447                    2128446, 2128447   True
2  2128500                    2128503, 2128508  False

或。

df['Match'] = df.apply(lambda x: str(x['ID']) in x['Multiple_IDs'], axis=1)
print (df)
        ID                        Multiple_IDs  Match
0  2128441  2128442, 2128443, 2128444, 2128441   True
1  2128447                    2128446, 2128447   True
2  2128500                    2128503, 2128508  False

另一个想法是用拆分值进行匹配。

df['Match'] = [str(x) in y.split(', ') for x, y in df[['ID','Multiple_IDs']].to_numpy()]

df['Match'] = df.apply(lambda x: str(x['ID']) in x['Multiple_IDs'].split(', '), axis=1)

1
投票

我要做的是

s=pd.DataFrame(df.Multiple_IDs.str.split(', ').tolist(),index=df.index).eq(df.ID.astype(str),axis=0).any(1)
Out[10]: 
0     True
1     True
2    False
dtype: bool
df['Match']=s
© www.soinside.com 2019 - 2024. All rights reserved.