Home > Net >  Add new columns to dataframe from dictionary for every row
Add new columns to dataframe from dictionary for every row

Time:05-23

I want to add columns in a dataframe from a dictionary where keys are randomly generated and for every row of the dataframe the values of keys should be added

products = {'Blue Racks': 6, 'HPT': 6, 'Plastic Pallet': 40, 'Trolley': 48}

and the dataframe is like following:

                  tag epc                   code             Location  
0           0  E200001B2003006506902124  PPRFP.1T22AD0001      Goa   
1           1  E200001B2001007523803291  PPRFP.1T22AD0002      Goa   
2           2  E200001B2003005907402139  PPRFP.1T22AD0003      Goa   
3           3  E200001B200302290510CF16  PPRFP.1T22AD0004      Goa   
4           4  E200001B20010114231054DD  PPRFP.1T22AD0005      Goa   

How can I do it ?

expecetd outcome:

         tag epc                   code           Location Blue Racks HPT Plastic Pallet
  E200001B2003006506902124  PPRFP.1T22AD0001      Goa        6  6 40
  E200001B2001007523803291  PPRFP.1T22AD0002      Goa        6  6  40
  E200001B2003005907402139  PPRFP.1T22AD0003      Goa        6  6 40
  E200001B200302290510CF16  PPRFP.1T22AD0004      Goa        6  6 40
  E200001B20010114231054DD  PPRFP.1T22AD0005      Goa        6  6  40
    

CodePudding user response:

You can craft a DataFrame from the dictionary and use a cross merge:

df2 = df.merge(pd.DataFrame(products, index=[0]), how='cross')
# or
# df.merge(pd.DataFrame([products]), how='cross')

output:

   tag                       epc              code Location  Blue Racks  HPT  \
0    0  E200001B2003006506902124  PPRFP.1T22AD0001      Goa           6    6   
1    1  E200001B2001007523803291  PPRFP.1T22AD0002      Goa           6    6   
2    2  E200001B2003005907402139  PPRFP.1T22AD0003      Goa           6    6   
3    3  E200001B200302290510CF16  PPRFP.1T22AD0004      Goa           6    6   
4    4  E200001B20010114231054DD  PPRFP.1T22AD0005      Goa           6    6   

   Plastic Pallet  Trolley  
0              40       48  
1              40       48  
2              40       48  
3              40       48  
4              40       48  

renaming original columns if existing in the dictionary:

df2 = (df.rename(columns=lambda x: x '_original' if x in products else x)
         .merge(pd.DataFrame(products, index=[0]), how='cross')
       )

CodePudding user response:

I guess if you're using panda, you could try and read the key and values of your dictionnary, then add for each key 5 times the corresponding value :

for key, value in products :
    new_column_value = []
    for i in range(5):
        new_column_value.append(value)
    df[key] = new_column_value
  • Related