Py学习  »  Python

如何用python分析二进制时间序列

sae220 • 3 年前 • 1328 次点击  

我希望你能原谅我糟糕的英语。

我想用Python(Pandas)分析二值化的时间序列数据,如下所示。

>>> import pandas as pd
>>> 
>>> s = pd.Series([0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0])
>>> type(s)
<class 'pandas.core.series.Series'>
>>> s
0     False
1     False
2     False
3      True
4      True
5      True
6      True
7     False
8     False
9     False
10    False
11     True
12     True
13    False
dtype: bool

我想提取值为真的索引的开始和结束。 我尝试了以下方法。

>>> diff = s.diff().dropna()
>>> diff
1     False
2     False
3      True
4     False
5     False
6     False
7      True
8     False
9     False
10    False
11     True
12    False
13     True
dtype: object
>>> idxs = diff[diff].index.to_series()
>>> idxs
3      3
7      7
11    11
13    13
dtype: int64
>>> events = pd.concat(
        [idxs[0::2].reset_index(drop=True),
            idxs[1::2].reset_index(drop=True)],
        axis=1)\
        .apply(lambda r: pd.Interval(r[0], r[1]), axis=1)
>>> events
0      (3, 7]
1    (11, 13]
dtype: interval

通过这种方式,我成功地提取了数据。 然而,这段代码似乎有点难看。 我认为可能会有更好的代码或库来实现这一点。

如果你知道的话,如果你能告诉我,我将不胜感激。 我也不知道 type(events) == pd.Series[pd.Interval] 是合适的,请给我一个更好的主意。 当然,要分析的实际数据要大得多。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132208
 
1328 次点击  
文章 [ 1 ]  |  最新文章 3 年前