简体   繁体   English

变换计数连续整数

[英]transform Count consecutive integers

i have a dataset like我有一个像

id
1
2
3
4
7
8

i want my output as:我希望我的输出为:

id   count
1     4
2     4
3     4
4     4
7     2
8     2

Thanks in advance提前致谢

Create Series for consecutive integers by Series.diff , compare for not equal 1 by Series.ne and add cumulative sum by Series.cumsum :创建Series由连续整数Series.diff ,比较不等于1Series.ne并添加累积和Series.cumsum

s = df['id'].diff().ne(1).cumsum()

Then use Series.map with Series.value_counts :然后使用Series.mapSeries.value_counts

df['count'] = s.map(s.value_counts())

Or GroupBy.transform with GroupBy.size :GroupBy.transformGroupBy.size

df['count'] = s.groupby(s).transform('size') 

print (df)
   id  count
0   1      4
1   2      4
2   3      4
3   4      4
4   7      2
5   8      2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM