社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

sae220 • 3 年前 • 1284 次点击  

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

我想用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
 
1284 次点击  
文章 [ 1 ]  |  最新文章 3 年前
mozway
Reply   •   1 楼
mozway    3 年前

这里有一个替代方案:

pd.Series([pd.Interval(x.index[0], x.index[-1]+1)
           for _,x in s[s].groupby((~s).cumsum())])

或者,如果没有范围索引:

m = s|s.shift()
pd.Series([pd.Interval(x.index[0], x.index[-1])
           for _,x in s[m].groupby((~m).cumsum())])

输出:

0      (3, 7]
1    (11, 13]
dtype: interval

使用的输入:

s = pd.Series([0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0]).astype(bool)