如何基于字符串包含合并两个数据帧?



我有 2 个数据帧,我想根据字符串包含将其合并到特定列上。这似乎是以下问题,但顺序不同:如何在字符串包含上合并熊猫?

import pandas as pd
df1 = pd.DataFrame({'Amount':[10, 20, 30], 'Description':['this is a text','this is another text','this is an important']})
df2 = pd.DataFrame({'Text':['another','important'], 'Category':['Another Category','Important Category']})
rhs = (df1.Description
.apply(lambda x: df2[df2['Category']] if df2[df2['Text']] in str(x).lower() else None)
)
(pd.concat([df1.Amount, rhs], axis=1, ignore_index=True)
.rename(columns={0: 'Amount', 1: 'Category'}))

我收到以下错误消息:

KeyError: "None of [Index(['another', 'important'], dtype='object')] are in the [columns]"

这是因为 lambda 表达式而发生的。对于 df2[df2['文本']] 部分,我尝试遍历包含类别的数据帧,但这不起作用。

假设 df2 是一个独特的文本表及其类别,我想这可以工作。(假设DFS与您发布的内容相同(

join_map = {row['Text']:row['Category'] for ind,row in df2.iterrows()}
df1['Category'] = df1['Description'].apply(lambda x: [val for key,val in join_map.items() if key in x][0] if [val for key,val in join_map.items() if key in x] else None)

最新更新