簡體   English   中英

熊貓DataFrame列中特定值的連續行的累積計數

[英]Cumulative count for consecutive rows of a specific value in a pandas DataFrame column

我有此數據框,並希望添加另一列累加直到不等於星形符號* ,然后在星形符號再次出現時從1繼續。

    Star
0   *
1   *
2   *
3   *
4   s
5   s
6   *
7   *

預期輸出:

    Star  Number
0   *     1
1   *     2
2   *     3
3   *     4
4   s     NaN
5   s     NaN
6   *     1
7   *     2

這是一個簡單的groupby和屏蔽操作。

m = df.Star.ne('*')
# Big thanks to @W-B for the bug fix!
df['Number'] = df[~m].groupby(m.cumsum()).cumcount().add(1)


df
  Star  Number
0    *     1.0
1    *     2.0
2    *     3.0
3    *     4.0
4    s     NaN
5    s     NaN
6    *     1.0
7    *     2.0

來自itertools groupby

import itertools
df['New']=sum([list(range(len(list(y)))) for _ , y in itertools.groupby(df.Star.tolist())],[])
df.loc[df.Star.ne('*'),'New']=np.nan
df.New+=1
df
Out[1152]: 
  Star  New
0    *  1.0
1    *  2.0
2    *  3.0
3    *  4.0
4    s  NaN
5    s  NaN
6    *  1.0
7    *  2.0

暫無
暫無

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

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