我有一个数据集
id
1
2
3
4
7
8
我希望我的输出为:
id count
1 4
2 4
3 4
4 4
7 2
8 2
提前致谢
最佳答案
通过 Series.diff
为连续整数创建 Series
, 比较 Series.ne
不等于 1
并通过 Series.cumsum
添加累计和:
s = df['id'].diff().ne(1).cumsum()
然后使用Series.map
与 Series.value_counts
:
df['count'] = s.map(s.value_counts())
或GroupBy.transform
与 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
关于python - 变换计数连续整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64118812/