![](/img/trans.png)
[英]Efficiently calculate non-consecutive number of appereances of element in data frame
[英]How to effciently calculate non-consecutive number of appereances of element in list?
所以我試圖找出某個元素沒有連續出現在列表中的次數。 我的意思是:
list = [10,10,10,11,12,10,12,14,10,10,10]
element_searched = 10
=> expected_output = 3
所以這意味着 10 在列表中出現了 3 次。
到目前為止,我的代碼似乎有效:
elements = [11, 10, 12]
row = [10,10,10,10,10,10,10,10,10,11,11,11,11,11,10,10,10,10,12,12,12,12,12,11,11,11,11,12,12,12,12,10]
element_on = False
for element in elements:
sequence = 0
for i in range(len(row)):
if element == row[i] and element_on==False:
sequence += 1
element_on = True
elif element==row[i] and element_on==True:
pass
elif element != row[i] and element_on==True:
element_on = False
#
elif element != row[i] and element_on == False:
element_on = False
#
print(f"For element {element} the number ob sequences is: {sequence} ")
我得到了所需的輸出,但我想知道是否有更優雅,尤其是更快的方法。
嘗試這個:
row = [10,10,10,10,10,10,10,10,10,11,11,11,11,11,10,10,10,10,12,12,12,12,12,11,11,11,11,12,12,12,12,10]
sr = pd.Series(row, name = "x")
sr[sr.groupby(sr.shift(-1).bfill(0).ne(sr)).transform('cumcount')==1].value_counts()
輸出:
10 3
12 2
11 2
第一列是x
值,第二列是序列數。
更緊湊、更快捷的方式:
from itertools import groupby
pd.Series([k for k, g in groupby(row)]).value_counts()
另一種解決方案:
np.unique([k for k, g in groupby(row)], return_counts=True)
結果:
(array([10, 11, 12]), array([3, 2, 2], dtype=int64))
或者使用np.bincount
:
np.bincount([k for k, g in groupby(row)])
但輸出會略有不同:
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 2], dtype=int64)
我想這就是你想要的。 按相似元素對列表進行分組,然后對計數求和
import itertools
element_searched = 10
expected_output = sum([i.count(element_searched) for i in itertools.groupby(list)])
3
我會使用一個簡單的字典:
row = [10,10,10,10,10,10,10,10,10,11,11,11,11,11,10,10,10,10,12,12,12,12,12,11,11,11,11,12,12,12,12,10]
counter = {}
last_item = None
for item in row:
if last_item != item:
counter[item] = counter.get(item, 0) + 1
last_item = item
print (counter)
一些可以指導您的想法:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.