【问题标题】:Finding the common elements in 2 columns which is present in a single dataframe查找单个数据框中存在的 2 列中的公共元素
【发布时间】:2021-11-28 21:16:14
【问题描述】:

[数据框的图像]

我想找到top30和玩过的游戏列中的共同元素

我使用了下面的代码,但它没有给我正确的输出

output : {f, 1, , ,, a, s, t, r, g, 2, ', y, o, e, [

我正在寻找的输出是

Prediction1['precision_at_30'] = [
    set(a).intersection(b) for a, b in zip(Prediction1['played_games'], Prediction1['top 30'])]

【问题讨论】:

标签: python pandas recommendation-engine


【解决方案1】:

您可以使用apply 来检查set 的交叉点:

df['result'] = df.apply(lambda r: set(r['games']).intersection(r['played_games']), axis=1)

例子:

             games played_games      result
0  [abc, def, ghi]   [def, abc]  {abc, def}

【讨论】:

  • 我认为屏幕截图显示了列表的字符串表示,因为我们可以看到单引号。试试看:df = pd.DataFrame({'colA': ["['abc', 'def']", ['ghi', 'jkl']]})
  • 是的,我认为你是对的,在这种情况下,OP 有你的答案。再举一个例子说明为什么提供数据图像是不好的做法。
  • 不幸的是,你是对的。也许有一天,有人会写一篇教程从notebook / excel到stackoverflow :)
  • 感谢您的回复,但我以这种方式得到了输出 {o, c, ], i, , t, s, 1, j, f, ,, e, h, r, a,
【解决方案2】:

您的列似乎是列表的字符串表示形式,因此您可以在使用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

【讨论】:

  • {o, c, ], i, , t, s, 1, j, f, ,, e, h, r, a, -> 谢谢,但我以这种方式得到输出是错误的,是的,我给出了错误的屏幕截图,它是一个包含字符串的列表
  • 当我使用您的代码片段时,我收到错误消息“NumExpr 2 不支持 Unicode 作为 dtype。”
  • 使用Prediction2.head(5).to_dict('list')的输出更新您的帖子
  • 嗨 corralien ,您可以检查我的数据框。 github.com/ajayvd/stack-overflow(附上数据框,因为截图有误)
  • 感谢您的帮助,现在它工作正常我已转换为来自 ast import literal_eval df = pd.read_csv('result.csv', converters={'top 30': literal_eval 的值列表,'played_games':literal_eval})
猜你喜欢
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
  • 2017-12-08
  • 1970-01-01
  • 2017-12-23
相关资源
最近更新 更多