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

Time:01-04

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'])

CodePudding user response:

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)
  •  Tags:  
  • Related