Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. Product Qty Dummy
  2. A 10 0
  3. B 15 0
  4. B 5 1
  5. C 5 0
  6. D 5 0
  7. D 20 1
  8.  
  9. Product Qty_pct
  10. B 0.25
  11. D 0.8
  12.  
  13. df2=df.pivot_table(columns='Dummy',index='Product',aggfunc='sum',values=['Qty']).reset_index()
  14. df2['Qty_pct']=df2['Qty'][1]/(df4['Qty'][1]+df2['Qty'][0])
  15. df2.columns=df2.columns.get_level_values(0)
  16.  
  17. df = pd.DataFrame({
  18. 'Product': ['A', 'B', 'B', 'C', 'D', 'D'],
  19. 'Qty': [10, 15, 5, 5, 5, 20],
  20. 'Dummy': [0, 0, 1, 0, 0, 1]
  21. })
  22.  
  23. # Create new column = Dummy*Qty
  24. df['DQty'] = df['Dummy'] * df['Qty']
  25.  
  26. # Groupby df by 'Product' and summarize columns
  27. df2 = df.groupby('Product').sum()
  28.  
  29. # Create new column equal to percentage of the total quantities
  30. df2['Q'] = df2['DQty'] / df2['Qty']
  31.  
  32. # Drop unnecessary columns
  33. df2 = df2.drop(columns=['Dummy', 'Qty', 'DQty'])
  34.  
  35. # Drop rows equal to zero
  36. df2 = df2.loc[df2['Q'] != 0]
  37. df2
  38.  
  39. Q
  40. Product
  41. B 0.25
  42. D 0.80
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement