pandas中如何基于另一DataFrame的匹配条件更新当前DataFrame数据
错误原因
你原来的代码直接对两个不同长度、不同索引的Series做等值比较,pandas会先按索引对齐两个序列,对齐失败就会抛出ValueError: Can only compare identically-labeled Series objects错误。
正确实现方案
我们可以通过左连接匹配两个表的text和pred字段,再用匹配到的Sentiment值替换原表数据,具体代码如下:
首先构造样例数据(修正原代码的拼写和语法错误):
import pandas as pd df_source = pd.DataFrame({ 'Sentiment':['neg', 'neg','pos'], 'text': ['hello ', '12where', 'here [null]'], 'pred': ['neu', 'neg', 'pos'] }) df2 = pd.DataFrame({ 'Sentiment':['pos', 'neg','pos', 'neu'], 'text': ['hello ', '12 where I', 'hello g* ', 'here [null]'], 'pred': ['neu', 'neg', 'neu', 'neu'] })
核心处理逻辑:
# 重命名df2的Sentiment列避免冲突 df2_temp = df2.rename(columns={'Sentiment': 'matched_Sentiment'}) # 以text和pred为关联键做左连接 merged_df = df_source.merge(df2_temp, on=['text', 'pred'], how='left') # 匹配到值就替换,没匹配到保留原值 df_source['Sentiment'] = merged_df['matched_Sentiment'].fillna(merged_df['Sentiment'])
最终输出df_source的结果:
Sentiment text pred 0 pos hello neu 1 neg 12where neg 2 pos here [null] pos
内容的提问来源于stack exchange,提问作者sariii
相关产品推荐
相关产品推荐

