简体   繁体   中英

Comma Separated String of ids map to values in python Pandas

I have a comma separated string in a columns in pandas DataFrame:

表格1

I have a mapping Dataframe

映射表

I want the final Dataframe:

价值观

I want a new column and replace the ids with values from the mapping dataframe, what is the write pythonic + pandas way to implement this?

You can use pd.Series.str.split , replace and join back into str:

df = pd.DataFrame({"Index":[0,1], "ids":["1,2,3", "1,2,3"]})
df2 = pd.DataFrame({"id":[1,2,3], "value":["value1", "value2", "value3"]})

df["value"] = (df["ids"].str.split(",", expand=True).astype(int)
                        .replace(df2.set_index("id")["value"])
                        .agg(lambda d: ",".join(i for i in d if isinstance(i, str)), axis=1))

print (df)

   Index    ids                 value
0      0  1,2,3  value1,value2,value3
1      1  1,2,3  value1,value2,value3

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