我有以下python pandas数据帧:
| Number of visits per year |
user id | 2013 | 2014 | 2015 | 2016 |
A 4 3 6 0
B 3 0 7 3
C 10 6 3 0
我想根据访问次数计算返回用户的百分比。对不起,我还没有任何代码,我不知道如何开始。在
这是我要寻找的最终结果:
^{pr2}$因此,根据上述情况,我可以说,2013年4次光顾该店的客户中,有15%的人在2014年再次光顾该店。在
非常感谢。在
更新:这就是我所做的,也许有更好的方法通过一个循环?在
每年,我都有一个这样的csv:
user_id | NR_V
A 4
B 3
C 10
NR_V代表访问次数。在
所以我上传了每个csv作为它自己的df,我有df_2009,df_2010。。。直到2016年。在
对于每一个文件,我添加了一个列列,如果他们第二年购买的话,则为0/1。在
df_2009['shopped2010'] = np.where(df_2009['user_ID'].isin(df_2010['user_ID']), 1, 0)
然后我旋转每个数据帧。在
pivot_2009 = pd.pivot_table(df_2009,index=["NR_V"],aggfunc={"NR_V":len, "shopped2010":np.sum})
接下来,对于每个数据帧,我创建了一个新的数据帧,其中包含一个按访问次数计算百分比的列。在
p_2009 = pd.DataFrame()
p_2009['%returned2010'] = (pivot_2009['shopped2010']/pivot_2009['NR_V'])*100
最后,我将所有这些数据帧合并为一个。在
dfs = [p_2009, p_2010, p_2011, p_2012, p_2013, p_2014, p_2015 ]
final = pd.concat(dfs, axis=1)
考虑示例访问数据帧
df
{8的条目代表8次独立的访问,它应该计数8次。我将使用
^{pr2}$repeat
在value_counts
之前完成此操作我使用了每个访问者的索引值,并检查了下一年相同的索引值(也就是相同的vistor_ID)是否大于0。然后以True或False的形式将其添加到字典中,您可以将其用于条形图。我还列出了两个列表(times\u return和return-at-u-all),用于额外的数据操作。在
请在下面找到我的解决方案。作为一个说明,我非常肯定这是可以改进的。在
相关问题 更多 >
编程相关推荐