【问题标题】:Is there a method to aggregate time series in pandas based on the sequential count of an occurrence?有没有一种方法可以根据出现的顺序计数来聚合 pandas 中的时间序列?
【发布时间】:2022-01-19 17:54:12
【问题描述】:

我正在 Pandas 中寻找一种方法来计算时间序列中特定值的连续出现次数。

假设我正在进行一项实验,我掷硬币并得到正面或反面(1 或 0)。我将我的结果记录在 pandas 系列中,我希望看看我有多少个实例(计数)有两个连续的头、三个连续的头、四个连续的头等等。此外,我希望它是一种滚动计数,这意味着形式的序列(尾、头、头、头、尾)将返回成对出现的两个正面实例的计数,以及一个单次计数三个头系列。

有没有一种自然的方法可以使用 Series/DataFrame 中的方法来做到这一点?我可以用一些 for 循环来做到这一点,但我担心这样做的成本。

谢谢。

编辑:请求的输入/输出。

输入:

a = pd.DataFrame({'coin' : [0,1,1,1,0]})
print(a.summary_of_windows())

输出:

{1: 3
 2: 2,
 3: 1}

输出可以是字典:键 1 表示出现正面,其中出现了三个。键 2 表示成对的连续磁头(其中有两个),键 3 表示长度为 3 的磁头序列(发生一次)。

【问题讨论】:

  • 您可以添加示例数据框和示例预期输出数据框吗?
  • @user17242583 完成

标签: python pandas time-series


【解决方案1】:

你可以使用DataFrame.rolling:

>>> df
   coin
0     0
1     1
2     1
3     1
4     0

# Compute how many sequences of two heads there are:
>>> df['coin'].rolling(2).sum().eq(2).sum()
2

# Do it for three sequences:
#   remember to change v    AND    v
>>> df['coin'].rolling(3).sum().eq(3).sum()
1

# Find total number of heads occurences:
>>> df['coin'].sum()
3

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多