簡體   English   中英

如何計算熊貓系列中重復出現的相同值

[英]How to count recurring identical values in a Pandas Series

我有一個帶有True / False值的Pandas系列,我需要計算一個值與先前值相同的頻率。

每當值更改時,計數應從1重新開始。

pd.Series([True, False, False, False, True, True, False])

0     True        --> 1
1    False        --> 1
2    False        --> 2
3    False        --> 3
4     True        --> 1
5     True        --> 2
6    False        --> 1
dtype: bool

我嘗試了shift()和cumsum()的各種組合,但沒有成功。

有什么提示嗎?

麥酒

您可以按連續值創建組,並比較shift值和cumsum並將其用於cumcount

s = pd.Series([True, False, False, False, True, True, False])

s1 = s.groupby(s.ne(s.shift()).cumsum()).cumcount().add(1)
print (s1)
0    1
1    1
2    2
3    3
4    1
5    2
6    1
dtype: int64

詳情:

print (s.ne(s.shift()).cumsum())
0    1
1    2
2    2
3    2
4    3
5    3
6    4
dtype: int32

另一個解決方案是分別對TrueFalse計數,然后對輸出求和:

cm1 = s.cumsum()
s1 = cm1-cm1.where(~s).ffill().fillna(0)
cm2 = (~s).cumsum()
s2 = cm2-cm2.where(s).ffill().fillna(0)
s3 = s1.add(s2).astype(int)
print (s3)
0    1
1    1
2    2
3    3
4    1
5    2
6    1
dtype: int32

詳情:

print (s1)
0    1.0
1    0.0
2    0.0
3    0.0
4    1.0
5    2.0
6    0.0
dtype: float64

print (s2)
0    0.0
1    1.0
2    2.0
3    3.0
4    0.0
5    0.0
6    1.0
dtype: float64

時間

np.random.seed(2018)
N = 1000000
s = pd.Series(np.random.choice([True, False], N))
#print (s)

def jez1(s):
    return s.groupby(s.ne(s.shift()).cumsum()).cumcount().add(1)

def jez2(s):
    cm1 = s.cumsum()
    s1 = cm1-cm1.where(~s).ffill().fillna(0)
    cm2 = (~s).cumsum()
    s2 = cm2-cm2.where(s).ffill().fillna(0)
    return s1.add(s2).astype(int)

print (jez1(s))
print (jez2(s))

In [173]: %timeit jez1(s)
1 loop, best of 3: 199 ms per loop

In [174]: %timeit jez2(s)
10 loops, best of 3: 92 ms per loop

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM