Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Product Qty Dummy
- A 10 0
- B 15 0
- B 5 1
- C 5 0
- D 5 0
- D 20 1
- Product Qty_pct
- B 0.25
- D 0.8
- df2=df.pivot_table(columns='Dummy',index='Product',aggfunc='sum',values=['Qty']).reset_index()
- df2['Qty_pct']=df2['Qty'][1]/(df4['Qty'][1]+df2['Qty'][0])
- df2.columns=df2.columns.get_level_values(0)
- df = pd.DataFrame({
- 'Product': ['A', 'B', 'B', 'C', 'D', 'D'],
- 'Qty': [10, 15, 5, 5, 5, 20],
- 'Dummy': [0, 0, 1, 0, 0, 1]
- })
- # Create new column = Dummy*Qty
- df['DQty'] = df['Dummy'] * df['Qty']
- # Groupby df by 'Product' and summarize columns
- df2 = df.groupby('Product').sum()
- # Create new column equal to percentage of the total quantities
- df2['Q'] = df2['DQty'] / df2['Qty']
- # Drop unnecessary columns
- df2 = df2.drop(columns=['Dummy', 'Qty', 'DQty'])
- # Drop rows equal to zero
- df2 = df2.loc[df2['Q'] != 0]
- df2
- Q
- Product
- B 0.25
- D 0.80
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement