【问题标题】:Intersection of list and dataframe, keeping duplicates of list but showing the values of a column in a dataframe列表和数据框的交集,保留列表的重复项,但显示数据框中列的值
【发布时间】:2021-10-16 02:49:34
【问题描述】:

找到了这个link,我的工作有点相似。

说我有:

x = ['the', 'the', 'and', 'a', 'apple', 'heart', 'heart']
y = {'words': ['the', 'belt', 'computer', 'heart','and'],'values':[3,2,1,1,4]}

使用上面链接中的建议,我得到了这个:

df = pd.DataFrame.from_dict(y)
items = set(df['words'])

found = [i for i in x if i in items] 
print(found)

结果是: ['the', 'the', 'and', 'heart', 'heart']

我希望能够得到单词的对应值,我卡住了。我想要的结果是这样的:

[3,3,4,1,1]

关于如何实现这一目标的任何想法?将不胜感激。

【问题讨论】:

    标签: python dataframe intersection


    【解决方案1】:

    你不需要熊猫。首先修改您的字典以将单词作为键,然后使用理解:

    y2 = dict(zip(*y.values()))
    [y2[i] for i in x if i in y2]
    

    输出:[3,3,4,1,1]

    pandas 中的(效率低得多)等价物是:

    s = df.set_index('words')['values']
    pd.Series(x).map(s).dropna()
    

    输出:

    0    3.0
    1    3.0
    2    4.0
    5    1.0
    6    1.0
    dtype: float64
    

    【讨论】:

    • 感谢您。我的数据实际上非常大(以千计)。使用 dict 比使用 pandas 更有效吗?
    • 数千并不多,您可以同时测试和比较。如果使用jupyter,可以在单元格开头写%%timeit来检查运行长度,如果是脚本,则有timeit模块
    • 惊人的速度!非常感谢!正在尝试很多代码,并尝试做for循环,并且运行了整个晚上,仍然只能处理2%。我是 python 的新手,因为我习惯于图形编程。感谢您的大力帮助!是时候重写我的程序了。
    • 不客气,编码愉快 ;)
    • 再次表示感谢!重新编写我的代码并运行它,并在几秒钟内完成整个数据集的运行。啊哈哈哈!惊人的!真的很想掌握python。我对它的能力感到惊讶,前提是必须知道正确的方法。向你致敬!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 2016-09-10
    • 2022-07-06
    • 2021-07-19
    • 2019-09-06
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多