我有兩個資料框,我想df_source根據兩個資料框中的條件更新一列:
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')})
我想根據此條件更新Sentimentin列df_source:如果兩個資料框中的文本完全相同并且 pred 列相同,則將 df_source 中的情緒替換為 df2 中的情緒
所以輸出將是這樣的(因為只有一個樣本滿足兩個條件“hello”):
Sentiment. text. pred
pos hello neu
neg 12where neg
pos here [null] pos
我做了什么:
df_source['Sentiment'] = df.where(((df['text']== df_source['text']) & (df['pred'] == dfs['pred'])) , df['Sentiment'])
它應該可以作業,但這會引發錯誤 ( ValueError: Can only compare identically-labeled Series objects)。
uj5u.com熱心網友回復:
首先在兩列和后綴上合并。
df_source = df_source.merge(df2, how ='left', on =['text', 'pred'], suffixes=('_x', ''))
使用 combine_first 替換不匹配的 NaN,然后??洗掉額外的合并列
df_source =df_source.assign(Sentiment= df_source['Sentiment'].combine_first(df_source.Sentiment_x) ).drop('Sentiment_x',1)
text pred Sentiment
0 hello neu pos
1 12where neg neg
2 here [null] pos pos
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/312994.html
上一篇:使用apply從其他表中查找資料
下一篇:替換兩個資料幀之間的單個單元格值
