简体   繁体   English

熊猫根据另一列的值创建条件列

[英]Pandas creating a conditional column based on the value of another column

I have two df's 我有两个df

df1: DF1:

index    text
1        string1
2        string2
3        string3
4        a
5        string5
6        a

df2: DF2:

index    text
4        string4
6        string6

How can I replace the text 'a' in df1 with the values found in df2 based on the index, so that it shows as below. 如何根据索引将df1中的文本“ a”替换为df2中的值,以便显示如下。

df3: DF3:

index    text
1        string1
2        string2
3        string3
4        string4
5        string5
6        string6

You can use pandas update as: 您可以将pandas update用作:

df1.set_index('index',inplace=True)
df2.set_index('index',inplace=True)
df1.update(df2) #df1 is changed

Or 要么

df1.loc[df2.index,'text'] = df2['text'] #df1 is changed

Or The output to be in df3 then 或者输出在df3中

df3 = df1.copy()
df3.update(df2) #df3 is changed

All of them produces: 它们全部产生:

       text
index   
1   string1
2   string2
3   string3
4   string4
5   string5
6   string6

This will work 这会起作用

pd.merge(df1[[]], df2, left_index=True, right_index=True)

or 要么

df2.loc[df1.index] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM