我正在分析一家商店的销售数据,我想计算在接下来的一个月里成为常客的“第一批顾客”的百分比。
我有一个包含所有订单的DataFrame。这包括客户id、日期和标志(如果这是他/她的第一个订单)。这是我的数据:
import pandas as pd
data = {'Name': ['Tom', 'nick', 'krish', 'Tom'],
'First_order': [1, 1, 1, 0],
'Date' :['01-01-2018', '01-01-2018', '01-01-2018', '02-02-2018']}
df = pd.DataFrame(data) 现在,我将在1月份创建一个所有新客户的列表,在2月份创建一个所有经常性客户的列表,并内部加入他们。然后我有两个数字,我可以用来计算百分比。
但我不知道如何在不循环数据帧的情况下计算整个一年的滚动。有没有一个很好的pandas/python方法来做到这一点呢?
我们的目标是有一个新的数据帧,其中包含月份和前一个月的经常性客户的百分比。
发布于 2019-09-06 22:23:33
一种想法是接受1月至11月的所有订单,并有一个"reccurr“列,它根据该客户是否在下个月下订单来给出真/假。然后,您可以采用计数/总和为true/false的每月groupby,并添加一个列,给出比率。
编辑:在此之前,您可能需要转换日期:
df.Date = pd.to_datetime(df.Date)然后:
df['month'] = df['Date'].apply(lambda x: x.month) #this is for simplicity's sake, not hard to extend to MMYYYY
df1 = df[df.month != 12].copy() #now we select everything but Nov
df1 = df1[df1.First_order == 1].copy() #and filter out non-first orders
df1['recurr'] = df1.apply(lambda x: True if len(df[(df.month == x.month + 1)&(df.Name == x.Name)])>0 else False, axis=1) #Now we fill a column with True if it finds an order from the same person next month
df2 = df1[['month','Name','recurr']].groupby('month').agg({'Name':'count','recurr':'sum'})此时,对于每个月,"Name“列具有第一个订单数,"recurr”列具有下个月再次订购的订单数。一个简单的额外列给出了百分比:
df2['percentage_of_recurring_customer'] = (df2.recurr/df2.Name)*100编辑:对于任意数量的日期,这里有一个笨拙的解决方案。选择一个开始日期,并使用该年的1月作为第1个月,然后按顺序对其后的所有月份进行编号。
df.Date = pd.to_datetime(df.Date)
start_year = df.Date.min().year
def get_month_num(date):
return (date.year-start_year)*12+date.month现在我们有了一个转换日期的函数,稍微修改了一下代码:
df['month'] = df['Date'].apply(lambda x: get_month_num(x))
df1 = df[df.First_order == 1].copy()
df1['recurr'] = df1.apply(lambda x: True if len(df[(df.month == x.month + 1)&(df.Name == x.Name)])>0 else False, axis=1)
df2 = df1[['month','Name','recurr']].groupby('month').agg({'Name':'count','recurr':'sum'})最后,您可以创建一个函数将月份数字还原为日期:
def restore_month(month_num):
year = int(month_num/12)+start_year #int rounds down so we can do this.
month = month_num%12 #modulo gives us month
return pd.Timestamp(str(year)+'-'+str(month)+'-1') #This returns the first of that month
df3 = df2.reset_index().copy() #removing month from index so we can change it.
df3['month_date'] = df3['month'].apply(lambda x: restore_month(x))https://stackoverflow.com/questions/57823209
复制相似问题