简体   繁体   中英

Map and merge values from another dataframe

1. input dataframe with random num values:

ID  num
a    2
a,b  3
b    1
c,e  4

I have another dataframe:

ID  name
a    a1
b    b5
c    c4
d    d1
e    e6

2. Expected result : I want to map the df1 with df2 on ID and stored as another column:

ID  num  ID_name
a    2    a1
a,b  3    a1,b5
b    1    b5
c,e  4    c4,e6

3.code i tried:

df1["ID_name"] = df1["ID"].map(df2)
df1

But the values are not getting mapped and showing NAN for most of the values

We can use Series.str.split then use Series.map and groupby on the elements.

df["ID_name"] = (
    df["ID"]
    .str.split(",")
    .explode()
    .map(df2.set_index("ID")["name"])
    .groupby(level=0)
    .agg(",".join)
)

    ID  num ID_name
0    a    2      a1
1  a,b    3   a1,b5
2    b    1      b5
3  c,e    4   c4,e6

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