简体   繁体   中英

Replace list of id in cell by matching value id another dataframe (pandas)

I have two dataframes, with one containing the corresponding value of the id and another one with the lists of id in each rows.

How can I replace the list of id by the matching values of the other dataframes?

df_1:

|      Id             |        Names     |     
| ------------------- | ---------------- |      
|          1          |         Name1    |     
|          2          |         Name2    |     
|          3          |         Name3    |     

df_2:

|      Id_lists       |  
| ------------------- |
|          [1]        |   
|          [2,3,1]    |        
|          [1,3 ]     |  

To create the dataframe in my exemple:

data = [[1, 'Name1'], [2, 'Name2'], [3,'Name3']]
data_2 = [[[1]],[[2,3,1]],[[1,3]]]
df_1 = pd.DataFrame(data, columns = ['Id', 'Names'])
df_2 = pd.DataFrame(data_2, columns = ['Id_lists'])

Try create the mapping dict with explode

map_dict = dict(zip(df1.Id,df1.Names))
df2['Names_lists'] =  df2['Id_lists'].explode().map(map_dict).groupby(level=0).agg(list)

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