简体   繁体   English

Count 满足条件的序列总数,不带for循环

[英]Count Total number of sequences that meet condition, without for-loop

I have the following Dataframe as input:我有以下数据框作为输入:

l = [2,2,2,5,5,5,3,3,2,2,4,4,6,5,5,3,5]
df = pd.DataFrame(l)
print(df)
    0
0   2
1   2
2   2
3   5
4   5
5   5
6   3
7   3
8   2
9   2
10  4
11  4
12  6
13  5
14  5
15  3
16  5

As an output I would like to have a final count of the total sequences that meet a certain condition.作为输出,我想对满足特定条件的总序列进行最终计数。 For example, in this case, I want the number of sequences that the values are greater than 3. So, the output is 3.例如,在这种情况下,我想要值大于 3 的序列数。因此,输出为 3。

  • 1st Sequence = [555]第一个序列 = [555]
  • 2nd Sequence = [44655]第二个序列 = [44655]
  • 3rd Sequence = [5]第三个序列 = [5]

Is there a way to calculate this without a for-loop in pandas ?有没有办法在 pandas 没有 for 循环的情况下计算这个? I have already implemented a solution using for-loop, and I wonder if there is better approach using pandas in O(N) time.我已经使用 for 循环实现了一个解决方案,我想知道在 O(N) 时间内使用 Pandas 是否有更好的方法。

Thanks very much!非常感谢!

Related to this question: How to count the number of time intervals that meet a boolean condition within a pandas dataframe?与此问题相关: 如何计算在熊猫数据框中满足布尔条件的时间间隔数?

You can use:您可以使用:

m = df[0] > 3
df[1] = (~m).cumsum()
df = df[m]
print (df)
    0  1
3   5  3
4   5  3
5   5  3
10  4  7
11  4  7
12  6  7
13  5  7
14  5  7
16  5  8


#create tuples
df  = df.groupby(1)[0].apply(tuple).value_counts()
print (df)

(5, 5, 5)          1
(4, 4, 6, 5, 5)    1
(5,)               1
Name: 0, dtype: int64

#alternativly create strings
df  = df.astype(str).groupby(1)[0].apply(''.join).value_counts()
print (df)

5        1
44655    1
555      1
Name: 0, dtype: int64

If need output as list:如果需要输出为列表:

print (df.astype(str).groupby(1)[0].apply(''.join).tolist())
['555', '44655', '5']

Detail:细节:

print (df.astype(str).groupby(1)[0].apply(''.join))

3      555
7    44655
8        5
Name: 0, dtype: object

If you don't need pandas this will suit your needs:如果您不需要pandas这将满足您的需求:

l = [2,2,2,5,5,5,3,3,2,2,4,4,6,5,5,3,5]

def consecutive(array, value):
  result = []
  sub = []
  for item in array:
    if item > value:
      sub.append(item)
    else:
      if sub:
        result.append(sub)
      sub = []
  if sub:
    result.append(sub)
  return result

print(consecutive(l,3))
#[[5, 5, 5], [4, 4, 6, 5, 5], [5]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM