![](/img/trans.png)
[英]Merge the rows of a df based on contiguous values of a particular column Pandas
[英]Counting number of contiguous column values in pandas df
我有一個像這樣的列的df:
col1
1
1
1
2
2
2
2
1
1
1
1
我想計算 col1 中每個值在某個閾值以上的連續出現次數。 因此,如果閾值為 0,則 output 應類似於:
1: 2
2: 1
如果閾值為 3,則 output 應類似於:
1: 1
2: 1
我知道循環列值並僅跟蹤連續鏈會起作用,但我想知道是否有 pandas 方法可以更快地做到這一點?
這是使用diff
和cumsum
創建附加密鑰的一種方法
s=df.groupby([df.col1,df.col1.diff().ne(0).cumsum()]).size()
s
Out[198]:
col1 col1
1 1 3
3 4
2 2 4
dtype: int64
thresh=3
s[s>thresh].count(level=0)
Out[201]:
col1
1 1
2 1
dtype: int64
從這里
df.col1.diff().ne(0).cumsum() # we bring the continue value into one value
Out[202]:
0 1
1 1
2 1
3 2
4 2
5 2
6 2
7 3
8 3
9 3
10 3
Name: col1, dtype: int32
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.