【问题标题】:Pandas | Compare two CSV files and return matches熊猫 |比较两个 CSV 文件并返回匹配项
【发布时间】:2020-09-29 23:25:19
【问题描述】:

所以我基本上是在尝试比较两个 CSV 文件并返回匹配项。

CSV1:包含关键字列表。

keywords

Apple
Banana
Orange

CSV2:包含随机内容。

content

I like Apples
Banana is my favorite Fruit
Strawberry Smoothies are the best

如果我像这样在代码中包含关键字...我会得到一个不错的结果。

import pandas as pd

df = pd.read_csv('CSV1.csv')
result = df[df.content.str.contains('Apple|Banana|Orange')]

由于关键字文件越来越大。我正在寻找一种从 csv 中提取关键字并检查匹配项的方法,而不是将所有关键字都放入代码中。

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    您可以通过使用 pandas isin() 函数 (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html) 来做到这一点

    伪代码是:

    # put the csv1's list to lower case
    list_csv1 = [i.lower() for i in list_csv1]
    
    # use the isin() function
    # again, put the content to lower case
    result = df[df.content.str.lower().isin(list_csv1)]
    

    将所有内容都小写不是强制性的,但这是规范数据和防止丢失的好方法。

    【讨论】:

      猜你喜欢
      • 2015-11-30
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多