pandas 如何使用python计算循环计数

bsxbgnwa  于 2022-12-16  发布在  Python
关注(0)|答案(1)|浏览(208)

我是python新手,我有大量的周期数据,需要计算周期下限小于5且周期上限介于21和22之间的递增周期峰值,必须将其检测为周期,我将此代码用作参考Counting loops/cycles of numbers in Python
我用的代码是

cycle= [0, 14,  9,  0,  0,  7,  0,  0, 12, 16, 15, 11,  7, 20, 24, 13, 13,
       14, 19, 13, 12, 10,  7,  3,  3,  3, 25, 14, 14, 14,  7, 24, 20, 20,
       21, 20, 20, 20, 20, 20, 21, 16, 11, 11, 18, 22, 22, 20, 19, 19, 18,
       15, 20, 23, 21, 23, 24, 15, 16, 19, 25, 24,  0, 20, 23, 24, 23, 22,
       21, 23, 25, 28, 24, 23, 23, 17,  7, 11, 21, 25, 25, 25, 25, 25, 25,
       15, 13,  9,  0, 21, 10, 18, 25, 25, 26, 23, 25, 23, 25, 27, 25, 12,
        0,  0,  0, 19, 22, 24, 25, 25, 24, 24, 23, 23, 16, 19, 23, 24, 24,
       17,  8,  0,  9,  7, 11, 18, 20, 23, 23, 24, 25, 25, 25, 17, 24, 24,
       25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 16,  0,  7, 14, 21, 26, 26,
       27, 28, 27, 15, 25, 26, 25, 25, 25, 24, 25, 25, 24, 26, 26, 26, 23]
sub_lists = np.split(cycle, np.where(np.diff(cycle) < 0)[0] + 1)
id_count = 0
id_list = []
for unit in sub_lists:
    if min(unit) >0 and max(unit) < 25 and len(set(unit)) > 1:
        id_count += 1
        id_list.append(unit)

但是由于在数据

中只有一个增加的周期

gajydyqb

gajydyqb1#

你在列表cycle的(5,25)中编码一个值。
如果你想得到递增循环的计数,并且循环的最小值〉5,循环的最大值〈25,你必须通过递增来分割循环列表。
1.你需要拆分周期列表

In [56]: cycle = [0, 14,  9,  0,  0,  7,  0,  0, 12, 16, 15, 11,  7, 20, 24, 13, 13]

In [57]: sub_lists = np.split(cycle, np.where(np.diff(cycle) < 0)[0] + 1)

In [58]: sub_lists
Out[58]:
[array([ 0, 14]),
 array([9]),
 array([0, 0, 7]),
 array([ 0,  0, 12, 16]),
 array([15]),
 array([11]),
 array([ 7, 20, 24]),
 array([13, 13])]

1.在sub_lists中查找所需范围

In [71]: id_count = 0
    ...: id_list = []
    ...: for unit in sub_lists:
    ...:     if min(unit) > 5 and max(unit) < 25 and len(set(unit)) > 1:
    ...:         id_count += 1
    ...:         id_list.append(unit)
    ...:
    ...:
    ...:

In [72]: id_count
Out[72]: 1

In [73]: id_list
Out[73]: [array([ 7, 20, 24])]

py文件中的代码为:
您需要先运行pip install numpy

import numpy as np
cycle = [0, 14,  9,  0,  0,  7,  0,  0, 12, 16, 15, 11,  7, 20, 24, 13, 13]
sub_lists = np.split(cycle, np.where(np.diff(cycle) < 0)[0] + 1)
id_count = 0
id_list = []
for unit in sub_lists:
    if min(unit) > 5 and max(unit) < 25 and len(set(unit)) > 1:
        id_count += 1
        id_list.append(unit)

相关问题