繁体   English   中英

如何以最小间隔将未排序的时间序列数据切割成箱?

[英]How to cut unsorted time-series data into bins with a minimum interval?

我有一个像这样的 dataframe

x = pd.DataFrame({'a':[1.1341, 1.13421, 1.13433, 1.13412, 1.13435, 1.13447, 1.13459, 1.13452, 1.13471, 1.1348, 1.13496,1.13474,1.13483,1.1349,1.13502,1.13515,1.13526,1.13512]})

我们如何拆分这个系列以获得以下 output 使得最小差异至少为 0.0005

x['output'] =  [1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0]

在此处输入图像描述

我不相信有一种矢量化的方式可以做到这一点,所以你可能需要遍历这些值。

x = x.assign(output=0)  # Initialize all the output values to zero.
x['output'].iat[0] = 1
threshold = 0.0005
prior_val = x['a'].iat[0]
for n, val in enumerate(x['a']):
    if abs(val - prior_val) >= threshold:
        x['output'].iat[n] = 1
        prior_val = val  # Reset to new value found that exceeds threshold.

这是我对矢量化和递归 function 的尝试。

递归 function 构建一行 dataframe 发送到调用者并在主 function 的末尾连接。

它使用在 0.24 版本中添加到 pandas 的可空 integer 类型。

编辑:这个解决方案比有循环的解决方案慢十倍。 你不应该使用它。

import pandas as pd


def find_next_step(df, initial_value, threshold):
    try:
        following_index = (
            df.loc[lambda x: (x['a'] - initial_value).abs() >= threshold]
            .loc[:, 'a']
            .index[0]
        )
    except IndexError:
        return []
    to_append = find_next_step(
        df.loc[following_index + 1:, :], x.loc[following_index, 'a'], threshold
    )
    to_append.append(
        pd.DataFrame({'output': [1]}, index=[following_index], dtype=pd.Int64Dtype())
    )
    return to_append


if __name__ == '__main__':
    x = pd.DataFrame({'a':[1.1341, 1.13421, 1.13433, 1.13412, 1.13435, 1.13447, 1.13459, 1.13452, 1.13471, 1.1348, 1.13496,1.13474,1.13483,1.1349,1.13502,1.13515,1.13526,1.13512]})
    output_list = find_next_step(x.iloc[1:, :], x.loc[:, 'a'].iloc[0], 0.0005)
    output_list.append(pd.DataFrame({'output': [1]}, index=[0], dtype=pd.Int64Dtype()))
    output_series = pd.concat(
        [x, pd.concat(output_list).sort_index()], axis='columns'
    ).assign(output=lambda x: x['output'].fillna(0))

它适用于您的示例,这将打印:

          a  output
0   1.13410       1
1   1.13421       0
2   1.13433       0
3   1.13412       0
4   1.13435       0
5   1.13447       0
6   1.13459       0
7   1.13452       0
8   1.13471       1
9   1.13480       0
10  1.13496       0
11  1.13474       0
12  1.13483       0
13  1.13490       0
14  1.13502       0
15  1.13515       0
16  1.13526       1
17  1.13512       0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM