您的列似乎是列表的字符串表示形式,因此您可以在使用set 谓词之前使用pd.eval 将您的字符串转换为真正的python 列表:
df = pd.DataFrame({'games': ["['abc', 'bef']", "['b', 'c', 'e', 'f']"],
'played_games': ["['abc', 'bef', 'e']", "['b', 'f']"]})
df['result'] = df[['games', 'played_games']].apply(
lambda x: set(pd.eval(x['games'])).intersection(pd.eval(x['played_games'])),
axis=1)
输出:
>>> df
games played_games result
0 ['abc', 'bef'] ['abc', 'bef', 'e'] {abc, bef}
1 ['b', 'c', 'e', 'f'] ['b', 'f'] {b, f}
更新:使用您的示例数据
df = pd.read_csv('https://raw.githubusercontent.com/ajayvd/stack-overflow/main/testing.csv', index_col=0)
df['result'] = df[['top 30', 'played_games']].apply(
lambda x: set(pd.eval(x['top 30'])).intersection(pd.eval(x['played_games'])),
axis=1)
print(df['result'])
# Output:
0 {fdtsl, ashhof, ctiv, aeolus, batcat, drgch, a...
1 {aogs, ashace, ashjut, bib, athn}
2 {aogs}
3 {ashjut, anwild}
4 {}
Name: result, dtype: object