【问题标题】:Check if text from one dataframe exists in another dataframe Python检查一个数据帧中的文本是否存在于另一个数据帧Python中
【发布时间】:2021-10-09 14:11:07
【问题描述】:

我是使用文本和 nlp 的新手,现在我有两个这样的数据框(原始数据非常大):

  1. DF
All_name Date Value
STEAM/BLIZZARD LLD -JOINT VENTURE 2001-08-03 Y
ACCO/SSD/HF CORP 2020-03-03 Y
ETIHAD/LUFTHANSA/HD LLC 2018-01-12 N
JOHN GROUP PLC/ROLLS-ROYCE PLC 2005-12-19 Y
FEDRA/KELL ELECTRONICS-STRATEGIC ALLIANCE 1999-09-27 N
CBC/MAFA STUDIOS {CBC/MAFA ENTERTAINMENT} 2013-06-24 N
  1. DF
Company another value
Soul Name Intertament 50
Etihad company 300
Rolls-Royce plc comp 8
Mafa corporation 1000
Aircorporation Lufthansa 12
Dll ltd 18
Airport Etihad 1
Hd corporation 743

我需要从 DF2 的“公司”列中检查 DF1 的“All_name”列中是否有公司。 如果它们在 DF1 中,结果必须类似于具有来自 DF2 的值的新数据框。这个例子看起来像:

DF_结果:

Company another value
Etihad company 300
Rolls-Royce plc comp 8
Mafa corporation 1000
Aircorporation Lufthansa 12
Airport Etihad 1
corporation Hd 743

困难在于数据帧中两列之间的差异,只有一些单词相似。我必须比较单词(?)或其他东西......

【问题讨论】:

  • 如何使用pd.merge,它基本上可以执行内部/外部连接。例如:在您的情况下,result = pd.merge(df2, df1, left_on='Company', right_on='All_name', how='inner')。但是,这需要在列之间进行精确的文本匹配,以便在两个数据框中获取公共数据
  • @tidakdiinginkan 列中的文字不同,只有一些词相似。我认为它不适用于这个:(
  • 是的,字符串与部分单词和表达式 b/w 数据帧匹配并非易事
  • @tidakdiinginkan 我明白了,因为它我写了例子:)

标签: python python-3.x pandas dataframe nlp


【解决方案1】:

这适用于这个数据集,但在大型数据集上使用它时要小心,因为它可能会给你一些误报,因为数据非常混乱:

df_1['All_name'] = df_1['All_name'].str.lower()
df_2['Soul Name Intertament'] = df_2['Soul Name Intertament'].str.lower()
all_companies = df_1['All_name'].str.split('/').explode().str.split(' ')

def apply_this(x):
    for company in all_companies:
        if len(set(x.split(' ')).intersection(set(company)))>=1:
            return True
    return False

df_result = df_2[df_2['Soul Name Intertament'].apply(lambda x: apply_this(x))]
print(df_result)

输出:

      Soul Name Intertament    50
0            etihad company   300
1      rolls-royce plc comp     8
2          mafa corporation  1000
3  aircorporation lufthansa    12
5            airport etihad     1
6            hd corporation   743

【讨论】:

  • 这是一个很好的例子,谢谢,但我有一个非常大的数据集。 :(
  • 那么你应该首先对你的数据集进行一些清理
猜你喜欢
  • 1970-01-01
  • 2022-11-28
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多