【问题标题】:Calculate Year on Year, Quarter on Quarter, Month on month number of Repeated, new, lost customers & theri revenue using pandas/python使用 pandas/python 计算每年、每季度、每月的重复客户、新客户、流失客户和其他收入的数量
【发布时间】:2022-11-12 08:01:35
【问题描述】:

我有客户的购买详情,这是我的数据结构

我试图逐年获取有多少客户总数,其中有多少是新的、重复的、失去的客户以及他们使用熊猫的收入。我也在寻找 Quater on Quarter 和 Month on Month 之后。

这是预期的输出模板。

我对熊猫很熟悉,在按订单日期分组后我是空白的,如何进一步进行。甚至我在想是否有可能使用 pandas/python 来获得这些滚动措施?

我进行了很多研究,但找到的解决方案并不可靠。 here 是其中之一使用 pandas,这是使用 sql 的用户尝试进行交叉连接的地方,这在我们拥有大型数据集时并不理想。

有人可以帮助我使用 pandas/python 获得一个合理的理想解决方案来解决这个问题吗?

【问题讨论】:

  • 欢迎Stack Overflow. 这不是代码编写或辅导服务。我们帮助解决具体的技术问题,而不是开放式的代码或建议请求。请编辑您的问题以显示您到目前为止尝试过的内容,以及您需要帮助解决的具体问题。有关如何最好地帮助我们帮助您的详细信息,请参阅How To Ask a Good Question 页面。

标签: python-3.x pandas


【解决方案1】:

这应该作为一个起点,您可以在 groupby 之后通过 .apply() 包含自定义函数,以映射丢失的客户数量和收入。

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

import pandas as pd
from io import StringIO

example = """
    customer    order_num   order_date  revenue year    previous_year
0   1   1   2001-03-02  3.7568075947151836  2001    2000
1   1   0   2001-07-05  26.100814373150747  2001    2000
2   0   0   2000-01-25  81.42727909292141   2000    1999
3   0   0   2002-10-27  84.57343031759379   2002    2001
4   1   0   2002-02-18  23.671899087103267  2002    2001
5   0   1   2002-09-25  74.49165102681509   2002    2001
6   0   1   2000-01-08  29.108785770121727  2000    1999
7   0   0   2000-11-17  58.09356390920113   2000    1999
8   1   1   2001-05-15  99.52589462159052   2001    2000
9   1   0   2002-12-08  44.19007228669444   2002    2001
"""
df = pd.read_csv(StringIO(example), sep='s+')
df

customer_year_counts = df.groupby('year')['customer'].value_counts()
customer_year_flags = customer_year_counts.unstack().diff().replace({np.nan: False}).stack()
customer_year_flags[customer_year_flags != False] = True
df['previous_year_active_flag'] = df.set_index(['year', 'customer']).index.map(customer_year_flags)
df['previous_year_active_flag'] = df['previous_year_active_flag'].replace({np.nan: False})

df = df.groupby(['customer', 'year', 'previous_year_active_flag']).agg(
    customer_count=pd.NamedAgg(column='customer', aggfunc='count'),
    revenue=pd.NamedAgg(column='revenue', aggfunc='sum'),
).unstack()

df['customer_count_total'] = df['customer_count'].sum(axis=1)
df['revenue_total'] = df['revenue'].sum(axis=1)

df.columns = [f'{i}_previous_year_active_{j}' if j != '' else f'{i}' for i,j in df.columns]

df.reset_index(inplace=True)
df

【讨论】:

    猜你喜欢
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 2019-07-02
    相关资源
    最近更新 更多