在python

时间:2018-06-01 06:47:52

标签: python python-3.x pandas group-by pivot-table

所以我在这里有一组50个日期,例如

df["CreatedDate"] = pd.DataFrame('09-08-16 0:00','22-08-16 0:00','23-08-16 0:00',28-08-16 0:00,'29-08-16 0:00','30-08-16 0:00','31-08-16 0:00')
df["CreatedDate"] = pd.to_datetime(df4.CreatedDate)
df4["DAY"] = df4.CreatedDate.dt.day

如何找到形成条纹范围的连续日[1-3],[4-7],[8-15],[> = 16]

 Streak Count 
 1-3     3    #(9),(22,23) are in range [1-3]
 4-7     1    #(28,29,30,31) are in range [4-7]
 8-15    0
 >=16    0

我们只是说产品(笔)已经推出2年了我们从今天开始使用数据集过去10个月,我想要找到的是如果人们连续购买1或2或3的笔天数,如果是,则计算[1-3],如果他们连续购买4或5天或6天或7天,我们将计数放在[4-7]中,依此类推其他范围

我不知道指定哪个条件符合条件

2 个答案:

答案 0 :(得分:1)

我认为需要:

df4 = pd.DataFrame({'CreatedDate':['09-08-16 0:00','22-08-16 0:00','23-08-16 0:00','28-08-16 0:00','29-08-16 0:00','30-08-16 0:00','31-08-16 0:00']})
df4["CreatedDate"] = pd.to_datetime(df4.CreatedDate)
df4 = df4.sort_values("CreatedDate")
count = df4.groupby((df4["CreatedDate"].diff().dt.days > 1).cumsum()).size()
print (count)
CreatedDate
0    2
1    4
2    1
dtype: int64

a = (pd.cut(count, bins=[0,3,7,15,31], labels=['1-3', '4-7','8-15', '>=16'])
       .value_counts()
       .sort_index()
       .rename_axis('Streak')
       .reset_index(name='Count'))
print (a)
  Streak  Count
0    1-3      2
1    4-7      1
2   8-15      0
3   >=16      0

答案 1 :(得分:0)

这是一次尝试,binning与@jezrael相同(除了我不确定应该限制在31的最后一个bin ...有没有办法打开pd.cut的间隔?)

import pandas as pd

df = pd.DataFrame({ "CreatedDate": ['09-08-16 0:00','22-08-16 0:00','23-08-16 0:00','28-08-16 0:00','29-08-16 0:00','30-08-16 0:00','31-08-16 0:00']})
df["CreatedDate"] = pd.to_datetime(df.CreatedDate)

# sort by date
df = df.sort_values("CreatedDate")

# group consecutive dates
oneday = pd.Timedelta("1 day")
df["groups"] = (df.diff() > oneday).cumsum()
counts = df.groupby("groups").count()["CreatedDate"]

# bin
streaks = (pd.cut(counts, bins=[0,3,7,15,1000000], labels=['1-3', '4-7','8-15', '>=16'])
           .value_counts()
           .rename_axis("streak")
           .reset_index(name="count"))

print(streaks)

  streak  count
0    1-3      2
1    4-7      1
2   >=16      0
3   8-15      0