python - 变换计数连续整数

标签 python pandas count transform

我有一个数据集

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.mapSeries.value_counts :

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

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

关于python - 变换计数连续整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64118812/

相关文章:

python - 如何用枕头调整图像大小?

python - 如何使用 Python 打开 Excel 文件以显示其内容?

python - 将 Pandas 数据框与 csv 文件进行比较的最佳方法

python - 比较列中的字符串并在 python 中创建相应的新列

对象的 Javascript 计数数组

r - 如何计算栅格堆栈列表中的栅格数量

python - 单击按钮后更改模型字段值

python - RLLib - Tensorflow - InvalidArgumentError : Received a label value of N which is outside the valid range of [0, N)

python - Pandas:对数据框中的行进行排序

mysql - 从单个表中获取不同记录的计数-MySQL