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
JavaScript
x
2
1
products = {'Blue Racks': 6, 'HPT': 6, 'Plastic Pallet': 40, 'Trolley': 48}
2
and the dataframe is like following:
JavaScript
1
7
1
tag epc code Location
2
0 0 E200001B2003006506902124 PPRFP.1T22AD0001 Goa
3
1 1 E200001B2001007523803291 PPRFP.1T22AD0002 Goa
4
2 2 E200001B2003005907402139 PPRFP.1T22AD0003 Goa
5
3 3 E200001B200302290510CF16 PPRFP.1T22AD0004 Goa
6
4 4 E200001B20010114231054DD PPRFP.1T22AD0005 Goa
7
How can I do it ?
expecetd outcome:
JavaScript
1
8
1
tag epc code Location Blue Racks HPT Plastic Pallet
2
E200001B2003006506902124 PPRFP.1T22AD0001 Goa 6 6 40
3
E200001B2001007523803291 PPRFP.1T22AD0002 Goa 6 6 40
4
E200001B2003005907402139 PPRFP.1T22AD0003 Goa 6 6 40
5
E200001B200302290510CF16 PPRFP.1T22AD0004 Goa 6 6 40
6
E200001B20010114231054DD PPRFP.1T22AD0005 Goa 6 6 40
7
8
Advertisement
Answer
You can craft a DataFrame from the dictionary and use a cross merge
:
JavaScript
1
4
1
df2 = df.merge(pd.DataFrame(products, index=[0]), how='cross')
2
# or
3
# df.merge(pd.DataFrame([products]), how='cross')
4
output:
JavaScript
1
14
14
1
tag epc code Location Blue Racks HPT
2
0 0 E200001B2003006506902124 PPRFP.1T22AD0001 Goa 6 6
3
1 1 E200001B2001007523803291 PPRFP.1T22AD0002 Goa 6 6
4
2 2 E200001B2003005907402139 PPRFP.1T22AD0003 Goa 6 6
5
3 3 E200001B200302290510CF16 PPRFP.1T22AD0004 Goa 6 6
6
4 4 E200001B20010114231054DD PPRFP.1T22AD0005 Goa 6 6
7
8
Plastic Pallet Trolley
9
0 40 48
10
1 40 48
11
2 40 48
12
3 40 48
13
4 40 48
14
renaming original columns if existing in the dictionary:
JavaScript
1
4
1
df2 = (df.rename(columns=lambda x: x+'_original' if x in products else x)
2
.merge(pd.DataFrame(products, index=[0]), how='cross')
3
)
4