【问题标题】:Python/Pandas matching substring in another substrings [closed]Python / Pandas在另一个子字符串中匹配子字符串[关闭]
【发布时间】:2021-02-23 08:07:07
【问题描述】:

我一直在寻找存储在 2 个不同数据帧的 2 个不同子项中的公共密钥,然后输出第三列:

import pandas as pd
import numpy as np
df1 = pd.DataFrame({'Name':['John','Michael','Dan','George', 'Adam'], 'Code1':['AAA OO','BBB UU','JJ',np.nan,'II']})

df2 = pd.DataFrame({'Second Name':['Smith','Cohen','Moore','Kas', 'Faber'], 'code2':['UU HHH','AAA GGG',np.nan , 'TT II', np.nan]})

预期输出:

我已经完成了我的研究.......问题与这个问题非常相似:How to merge pandas on string contains?。但是这里的键只有一个项目,我的示例在两个键中都有 2 个项目。

【问题讨论】:

  • 这能回答你的问题吗? Pandas Merging 101
  • 您好,不,谢谢,我在问如何匹配存储在 2 个子字符串中的公共密钥,我知道如何进行标准匹配。
  • @MayankPorwal 你好,他们共享相同的 AAA 代码。我找到了一种解决查询的方法,但前提是一个键在同一行中没有另一个代码。

标签: python pandas dataframe substring


【解决方案1】:

假设您的代码始终由空格分隔。

您可以使用list comprehensions 来检查Code2 列中Code1 列中的每个代码是否存在。通过检索匹配代码的索引,我们可以得到一个包含重叠代码行的Dataframe

然后我们可以更新原始数据框以获得预期的输出。

# Create a list of matching codes
list_of_matches = df1['Code1'].apply(lambda x: [
                         any([word in str(list_of_words).split() 
                              for word in str(x).split()]) 
                              for list_of_words in df2['code2']])

# Get the indices of matching codes
i, j = np.where(list_of_matches.values.tolist())

# Create a new dataframe with name and second name of rows with matching code
# And drop rows with NA, as they don't make sense
df3 = pd.DataFrame(np.column_stack([df1.loc[i], df2.loc[j]]), 
                   columns=df1.columns.append(df2.columns)).dropna()

# Create columns in your original dataframe to be able to update the dataframe
df1['Second Name'] = np.nan
df1['code2'] = np.nan

# Update dataframe with matching rows
df1.update(df3)

输出

    Name    Code1   Second Name   code2
0   John    AAA OO  Cohen         AAA GGG
1   Michael BBB UU  Smith         UU HHH
2   Dan     JJ      NaN           NaN
3   George  NaN     NaN           NaN
4   Adam    II      Kas           TT II

【讨论】:

    猜你喜欢
    • 2014-12-23
    • 2021-08-25
    • 2019-06-26
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    相关资源
    最近更新 更多