简体   繁体   中英

Pandas: assign value depending on another dataframe

I have to dataframes that look like this:

 df1:          condition        
               A               
               A              
               A               
               B              
               B             
               B           
               B   

 df2:          condition      value   
               A               1
               B               2

I would like to assign to each condition its value, adding a column to df1 in order to obtain:

 df1:          condition     value      
               A               1
               A               1
               A               1
               B               2
               B               2
               B               2
               B               2

how can I do this? thank you in advance!

Use map by Series created by set_index if need append one column only:

df1['value'] = df1['condition'].map(df2.set_index('condition')['value'])

print (df1)
  condition  value
0         A      1
1         A      1
2         A      1
3         B      2
4         B      2
5         B      2
6         B      2

Or use merge with left join if df2 have more columns:

df = df1.merge(df2, on='condition', how='left')
print (df)
  condition  value
0         A      1
1         A      1
2         A      1
3         B      2
4         B      2
5         B      2
6         B      2

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