[英]How can I get the difference between two month-year dates in streamlit?
事情是这样的,我正在构建一个 streamlit 应用程序来获取队列数据。 就像这里解释的那样: https://towardsdatascience.com/a-step-by-step-introduction-to-cohort-analysis-in-python-a2cbbd8460ea 。 所以,基本上我现在处于 dataframe 的地步,其中包含队列日期(队列)、属于该队列并在该月购买的客户数量(n_customers)和付款月份(订单月) ). 现在,我必须得到一个关于周期数的列。 我的意思是,我有这个:
cohort order_month n_customers
2009-12 2009-12 1045
2009-12 2010-01 392
2009-12 2010-02 358
.
.
.
我正试图得到这个:
cohort order_month n_customers period_number
2009-12 2009-12 1045 0
2009-12 2010-01 392 1
2009-12 2010-02 358 2
.
.
.
dataframe 的名称是 df_cohort。
因此,在 12/2009 月,队列 12/2009 中有 1045 位顾客购买了东西。 在 01/2010 月,队列 12/2009 中有 392 位顾客购买了东西。 等等。 我需要创建列period_number以构建我的热图。
我试着运行这个:
df_cohort["period_number"] = (
df_cohort - df_cohort
).apply(attrgetter("n"))
但是我得到了这个错误:
AttributeError: 'Timedelta' object has no attribute 'n'
我需要构建与教程略有不同的 dataframe,这就是我出现此错误的原因。 从现在开始有什么办法可以解决这个问题吗? 之前没有改变任何东西,但仅此而已。
关于每一列的数据类型,order_month和corhort都是datetime64[ns]。
您是否尝试过指定列? 喜欢
df_cohort['period_number'] = (df_cohort['invoice_month']-df_cohort['cohort']).apply(attrgetter('n'))
谢谢。
例如,您可以尝试应用一个 function 来创建这些句点
def cohort_period(df):
df['CohortPeriod'] = np.arange(len(df))+1
return df
cohorts = cohorts.groupby(level=0).apply(cohort_period)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.