大熊猫结合滚动和重采样

时间:2019-03-03 15:51:11

标签: pandas dataframe time-series resampling rolling-computation

我需要重采样和滚动功能之间的某种组合。 基本上,我需要滚动几秒(例如,每秒-在最近的X秒中计数唯一值),而我的数据精度是毫秒。因此,我需要每秒对一些记录进行分组(不进行汇总,这样我就不会丢失任何信息),然后将其翻转。

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

func setupAppFromDeeplink() {
    let tabBarController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "tabBar") as! UITabBarController
    let homeNavigationController = tabBarController.viewControllers?.first as! UINavigationController

    let firstVc = UIViewController() 
    let secondVc = UIViewController()
    let thirdVc = UIViewController()

    homeNavigationController.viewControllers = [firstVc, secondVc, thirdVc]

    window!.rootViewController = tabBarController
}

我想每隔一秒对过去2秒(窗口大小='2s')中的唯一值进行计数。

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

firstVc

代码将按如下所示对记录进行分组和分组(代码输出):

                         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

,输出结果如下:

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()

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


代码以生成数据框:

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]

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

相关问题