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
Advertisement
Answer
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') )