Objective: I have a pivot table, where I would like to divide each cell by a value from my dataframe, if there is a match.
Specifically, all the cells in the column 0 should be divided by 4 because Store1 is 4 in the dataframe. Similarly, the last column would be divided by 3.
The expected outcome is...
Data:
df = pd.DataFrame({'Start':['Store1','Store1','Store1','Store2','Store2','Store2','Store3','Store3','Store3'],
'Stop':['Store1','Store2','Store3','Store1','Store2','Store3','Store1','Store2','Store3'],
'Distance':[0,100,200,100,0,100,100,100,0]}).pivot(columns='Start', index = 'Stop', values=None)
df_div = pd.DataFrame({'Distance':['Store1','Store3'],'Import':[4,3]})
df_div = df_div.set_index('Distance')
Here's a solution with a for loop:
for store in df_div.index:
divider = df_div.loc[store,][0]
df.loc[:,(slice(None),store)] = df.loc[:,(slice(None),store)]/divider
Output of df :
Distance
Start Store1 Store2 Store3
Stop
Store1 0.0 100 33.333333
Store2 25.0 0 33.333333
Store3 50.0 100 0.000000
If you want to include only stores from df_div in df , you can use this outside the for loop:
df = df.loc[:,(slice(None),list(df_div.index))]
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.