Skip to main content
 首页 » 编程设计

python之Pandas 系列中重复出现的子系列摘要

2025年05月04日9zhenyulu

我希望获得 pandas 系列中指定长度的所有重复子系列的摘要。我想知道是否有一种方法可以在 pandas 模块中找到这些信息。此外,我想要一种报告每个子系列频率的方法(也许是直方图?)。谢谢!

例如:

    series =  
    0    a 
    1    b 
    2    b 
    3    b 
    4    a 
    5    b 
    6    b 
    7    a 
    8    b 
    9    a 
 
    subseries_frequency(series, 3) 

会返回:

    [a,b,b] = 2 
    [b,b,b] = 1 
    [b,b,a] = 2 
    [b,a,b] = 2 
    [a,b,a] = 1 

请您参考如下方法:

这样做会:

>>> from collections import Counter 
>>> pred = lambda t: not t[-1] != t[-1] # predicate to drop the partial ones 
>>> iter = (ts.shift(-j) for j in range(3))  
>>> Counter(filter(pred, zip(*iter))) 
Counter({('a', 'b', 'b'): 2, ('b', 'a', 'b'): 2, ('b', 'b', 'a'): 2, ('b', 'b', 'b'): 1, ('a', 'b', 'a'): 1}) 
>>> pd.Series(_) 
a  b  a    1 
      b    2 
b  a  b    2 
   b  a    2 
      b    1 
dtype: int64 

或者,

>>> iter = (ts.shift(-j) for j in range(3)) 
>>> cnt = pd.Series(list(zip(*iter))) 
>>> cnt.iloc[:-2].value_counts() 
(a, b, b)    2 
(b, a, b)    2 
(b, b, a)    2 
(b, b, b)    1 
(a, b, a)    1 
dtype: int64