gpt4 book ai didi

python - pandas 日期字段的 cut/qcut 等价于什么?

转载 作者:太空狗 更新时间:2023-10-29 21:34:52 25 4
gpt4 key购买 nike

更新:从版本 0.20.0 开始,pandas cut/qcut 确实可以处理日期字段。参见 What's New了解更多。

pd.cut and pd.qcut now support datetime64 and timedelta64 dtypes (GH14714, GH14798)

原始问题:Pandas cut 和 qcut 函数非常适合“分桶”连续数据以用于数据透视表等,但我看不到在混合。令人沮丧,因为 pandas 在所有与时间相关的事情上都非常出色!

这是一个简单的例子:

def randomDates(size, start=134e7, end=137e7):
return np.array(np.random.randint(start, end, size), dtype='datetime64[s]')

df = pd.DataFrame({'ship' : randomDates(10), 'recd' : randomDates(10),
'qty' : np.random.randint(0,10,10), 'price' : 100*np.random.random(10)})
df

price qty recd ship
0 14.723510 3 2012-11-30 19:32:27 2013-03-08 23:10:12
1 53.535143 2 2012-07-25 14:26:45 2012-10-01 11:06:39
2 85.278743 7 2012-12-07 22:24:20 2013-02-26 10:23:20
3 35.940935 8 2013-04-18 13:49:43 2013-03-29 21:19:26
4 54.218896 8 2013-01-03 09:00:15 2012-08-08 12:50:41
5 61.404931 9 2013-02-10 19:36:54 2013-02-23 13:14:42
6 28.917693 1 2012-12-13 02:56:40 2012-09-08 21:14:45
7 88.440408 8 2013-04-04 22:54:55 2012-07-31 18:11:35
8 77.329931 7 2012-11-23 00:49:26 2012-12-09 19:27:40
9 46.540859 5 2013-03-13 11:37:59 2013-03-17 20:09:09

要按价格或数量分组,我可以使用 cut/qcut 对它们进行分桶:

df.groupby([pd.cut(df['qty'], bins=[0,1,5,10]), pd.qcut(df['price'],q=3)]).count()

price qty recd ship
qty price
(0, 1] [14.724, 46.541] 1 1 1 1
(1, 5] [14.724, 46.541] 2 2 2 2
(46.541, 61.405] 1 1 1 1
(5, 10] [14.724, 46.541] 1 1 1 1
(46.541, 61.405] 2 2 2 2
(61.405, 88.44] 3 3 3 3

但我看不到任何简单的方法可以对我的“记录”或“发货”日期字段执行相同的操作。例如,生成一个类似的计数表,按(比如说)每月的 recd 和 ship 桶分割。似乎 resample() 拥有所有的机制来分阶段,但我不知道如何在这里应用它。 'date cut' 中的桶(或级别)相当于 pandas.PeriodIndex,然后我想用 df['recd'] 的每个值标记它落入的时间段?

所以我正在寻找的输出类型类似于:

ship    recv     count
2011-01 2011-01 1
2011-02 3
... ...
2011-02 2011-01 2
2011-02 6
... ... ...

更一般地说,我希望能够在输出中混合和匹配连续变量或分类变量。假设 df 还包含一个带有红色/黄色/绿色值的“状态”列,那么也许我想按状态、价格桶、发货和记录桶汇总计数,所以:

ship    recv     price   status count
2011-01 2011-01 [0-10) green 1
red 4
[10-20) yellow 2
... ... ...
2011-02 [0-10) yellow 3
... ... ... ...

作为奖励问题,修改上面的 groupby() 结果以仅包含一个名为“count”的输出列的最简单方法是什么?

最佳答案

这是一个使用 pandas.PeriodIndex 的解决方案(警告:PeriodIndex 不似乎支持倍数 > 1 的时间规则,例如“4M”)。我认为奖励问题的答案是 .size()

In [49]: df.groupby([pd.PeriodIndex(df.recd, freq='Q'),
....: pd.PeriodIndex(df.ship, freq='Q'),
....: pd.cut(df['qty'], bins=[0,5,10]),
....: pd.qcut(df['price'],q=2),
....: ]).size()
Out[49]:
qty price
2012Q2 2013Q1 (0, 5] [2, 5] 1
2012Q3 2013Q1 (5, 10] [2, 5] 1
2012Q4 2012Q3 (5, 10] [2, 5] 1
2013Q1 (0, 5] [2, 5] 1
(5, 10] [2, 5] 1
2013Q1 2012Q3 (0, 5] (5, 8] 1
2013Q1 (5, 10] (5, 8] 2
2013Q2 2012Q4 (0, 5] (5, 8] 1
2013Q2 (0, 5] [2, 5] 1

关于python - pandas 日期字段的 cut/qcut 等价于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16319106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com