簡體   English   中英

Count 滿足條件的序列總數,不帶for循環

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

我有以下數據框作為輸入:

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

作為輸出,我想對滿足特定條件的總序列進行最終計數。 例如,在這種情況下,我想要值大於 3 的序列數。因此,輸出為 3。

  • 第一個序列 = [555]
  • 第二個序列 = [44655]
  • 第三個序列 = [5]

有沒有辦法在 pandas 沒有 for 循環的情況下計算這個? 我已經使用 for 循環實現了一個解決方案,我想知道在 O(N) 時間內使用 Pandas 是否有更好的方法。

非常感謝!

與此問題相關: 如何計算在熊貓數據框中滿足布爾條件的時間間隔數?

您可以使用:

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

如果需要輸出為列表:

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

細節:

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

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

如果您不需要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