简体   繁体   中英

Assign value from one dataframe to another based on condition

df1

Severity Key
S3        1
S2        1
S3        2
S2        2
S1        3
S1        1
S3        3

df2

S1  S2  S3  Key
10  20  30   1
20  40  60   2
30  60  90   3

Output df that I'm expecting

Severity Key value
S3        1   30
S2        1   20
S3        2   60
S2        2   40
S1        3   30
S1        1   10
S3        3   90

Any help is appreciated and thanks in advance for the help

Try merge after melt :

df1.merge(df2.melt('Key',var_name='Severity'),on=['Severity','Key'])

Output:

  Severity  Key  value
0       S3    1     30
1       S2    1     20
2       S3    2     60
3       S2    2     40
4       S1    3     30
5       S1    1     10
6       S3    3     90

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