简体   繁体   中英

Add column from other data frame based on condition

I have two data frames:

df1 = 

ID  Num
a     0
b     0
c     1
d     1

And 2-nd:

df = 

ID
a
a
b
b
c
c
d

I want to add Num column to df with the following rule:

If in df1 a is 0 , then every a in df should be 0 and so on.


Desired output:

df1 = 

ID  Num
a     0
a     0
b     0
b     0
c     1
c     1
d     1

I did it with if condition, but it appears very long and hard coding

Try this:

nummap = df1.set_index('ID').to_dict()['Num']  
df['Num'] = df['ID'].map(nummap)  

output

In [387]: df                                                                                                                                                                                                
Out[387]: 
  ID  Num
0  a    0
1  a    0
2  b    0
3  b    0
4  c    1
5  c    1
6  d    1

Let us try merge

df=df.merge(df1)
  ID  Num
0  a    0
1  a    0
2  b    0
3  b    0
4  c    1
5  c    1
6  d    1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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