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
:
s = df['id'].diff().ne(1).cumsum()
Then use Series.map
with Series.value_counts
:
df['count'] = s.map(s.value_counts())
Or GroupBy.transform
with GroupBy.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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.