Advertisement
Guest User

WeeklyAnalysis.py

a guest
Feb 26th, 2020
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import matplotlib as mpl
  5.  
  6. df = pd.read_excel('LPWHistoricalData_MasterListWITHID.xlsx', encoding = "ISO-8859-1", dayfirst = True, infer_datetime_format = False)
  7. df.head()
  8. df['First_Order_Date'] = pd.to_datetime(df['First_Order_Date'])
  9. df['OrderPeriod'] = df.First_Order_Date.apply(lambda x: x.strftime('%Y-%W'))
  10. df.set_index('ID', inplace=True)
  11.  
  12. df['CohortGroup'] = df.groupby(level=0)['First_Order_Date'].min().apply(lambda x: x.strftime('%Y-%W'))
  13. df.reset_index(inplace=True)
  14. # exit(1)
  15. grouped = df.groupby(['CohortGroup', 'OrderPeriod'])
  16.  
  17. # count the unique users, orders, and total revenue per Group + Period
  18. cohorts = grouped.agg({'ID': pd.Series.count})
  19.  
  20. # make the column names more meaningful
  21. # cohorts.rename(columns={'ID': 'TotalUsers',
  22. # 'OrderId': 'TotalOrders'}, inplace=True)
  23. cohorts.head()
  24.  
  25. def cohort_period(df):
  26. """
  27. Creates a `CohortPeriod` column, which is the Nth period based on the user's first purchase.
  28.  
  29. Example
  30. -------
  31. Say you want to get the 3rd month for every user:
  32. df.sort(['UserId', 'OrderTime', inplace=True)
  33. df = df.groupby('UserId').apply(cohort_period)
  34. df[df.CohortPeriod == 3]
  35. """
  36. df['CohortPeriod'] = np.arange(len(df)) + 1
  37. return df
  38.  
  39. cohorts.to_csv("GregWeekly1.csv")
  40. cohorts = cohorts.groupby(level=0).apply(cohort_period)
  41. cohorts.head()
  42.  
  43.  
  44.  
  45.  
  46. cohorts.to_csv("GregWeekly2.csv")
  47.  
  48. cohorts.reset_index(inplace=True)
  49. let_see = cohorts.pivot(index='CohortGroup', columns='OrderPeriod', values='ID')
  50. # cohorts.set_index(['CohortGroup', 'CohortPeriod'], inplace=True)
  51.  
  52. let_see.to_csv("GregWeekly3.csv")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement