大熊猫结合滚动和重新采样

问题描述 投票:3回答:2

我需要在重采样和滚动功能之间进行一些组合。基本上我需要滚动秒(例如,每秒 - 在最后X秒计算唯一值),而我的数据精度是毫秒。所以我需要每秒进行一些记录分组(没有聚合,所以我不会丢失任何信息),然后滚动它们。

示例:假设我有以下数据帧,其中索引具有毫秒精度时间戳,数据是分类的(生成数据帧的代码如下):

                         A
2019-01-01 13:00:00.060  1
2019-01-01 13:00:00.140  2
2019-01-01 13:00:00.731  1
2019-01-01 13:00:01.135  2
2019-01-01 13:00:01.344  3
2019-01-01 13:00:02.174  2
2019-01-01 13:00:02.213  3
2019-01-01 13:00:02.363  2
2019-01-01 13:00:02.951  1
2019-01-01 13:00:03.393  4
2019-01-01 13:00:03.454  4
2019-01-01 13:00:04.444  4
2019-01-01 13:00:05.123  1
2019-01-01 13:00:05.456  4

我希望,每一秒钟,计算最后2秒的唯一值(窗口大小='2s')。

使用for循环看起来像这样:

from pandas.tseries.frequencies import to_offset

idx_seconds = df.index.ceil('s').unique()
output = pd.Series(index=idx_seconds)
for s in idx_seconds:
    print(f"{s-to_offset('2s')} - {s} -> {df.loc[s-to_offset('2s'):s, 'A'].to_list()}")
    output [s] = df.loc[s-to_offset('2s'):s, 'A'].nunique()

代码将拆分并将记录分组如下(代码输出):

2019-01-01 12:59:59 - 2019-01-01 13:00:01 -> [1, 2, 1]
2019-01-01 13:00:00 - 2019-01-01 13:00:02 -> [1, 2, 1, 2, 3]
2019-01-01 13:00:01 - 2019-01-01 13:00:03 -> [2, 3, 2, 3, 2, 1]
2019-01-01 13:00:02 - 2019-01-01 13:00:04 -> [2, 3, 2, 1, 4, 4]
2019-01-01 13:00:03 - 2019-01-01 13:00:05 -> [4, 4, 4]
2019-01-01 13:00:04 - 2019-01-01 13:00:06 -> [4, 1, 4]

输出看起来像:

2019-01-01 13:00:01    2.0
2019-01-01 13:00:02    3.0
2019-01-01 13:00:03    3.0
2019-01-01 13:00:04    4.0
2019-01-01 13:00:05    1.0
2019-01-01 13:00:06    2.0

我正在寻找一种不需要循环的更有效的解决方案。有什么建议?


用于生成数据帧的代码:

timestamps = [
'2019-01-01 13:00:00.060000', #0
'2019-01-01 13:00:00.140000', #0
'2019-01-01 13:00:00.731000', #0
'2019-01-01 13:00:01.135000', #1
'2019-01-01 13:00:01.344000', #1
'2019-01-01 13:00:02.174000', #2
'2019-01-01 13:00:02.213000', #2
'2019-01-01 13:00:02.363000', #2
'2019-01-01 13:00:02.951000', #2    
'2019-01-01 13:00:03.393000', #3
'2019-01-01 13:00:03.454000', #3    
'2019-01-01 13:00:04.444000', #4
'2019-01-01 13:00:05.123000', #5
'2019-01-01 13:00:05.456000', #5
]
df = pd.DataFrame([1, 2, 1, 2, 3, 2, 3, 2, 1, 4, 4, 4, 1 ,4]
                  ,columns=['A'], index=pd.to_datetime(timestamps)
pandas dataframe time-series resampling rolling-computation
2个回答
1
投票

来自numpy广播的一种方法

s1=idx_seconds.values
s2=(idx_seconds-to_offset('2s')).values
s=df.index.values

Outs=((s[:,None]-s2)/np.timedelta64(1, 'ns')>=0)&((s[:,None]-s1)/np.timedelta64(1, 'ns')<=0)

pd.Series([(df.A[x].nunique()) for x in Outs.T],index=idx_seconds )
2019-01-01 13:00:01    2
2019-01-01 13:00:02    3
2019-01-01 13:00:03    3
2019-01-01 13:00:04    4
2019-01-01 13:00:05    1
2019-01-01 13:00:06    2
dtype: int64

0
投票

试试df.resample('2s').nunique()

© www.soinside.com 2019 - 2024. All rights reserved.