Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 变换计数连续整数_Python_Pandas_Count_Transform - Fatal编程技术网

Python 变换计数连续整数

Python 变换计数连续整数,python,pandas,count,transform,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 提前感谢创建连续整数的系列,比较不相等的1by,并通过以下方式添加累积和: 然后与以下内容一起使用: 或与: 请尝试df['count']=df.groupby(df['id'].diff().ne(1.cumsum())['id'].transform('size')它已经起作用了。非常感谢你们两位:)

我有一个类似的数据集

id
1
2
3
4
7
8
我希望我的输出为:

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

提前感谢

创建连续整数的系列,比较不相等的1by,并通过以下方式添加累积和:

然后与以下内容一起使用:

或与:


请尝试
df['count']=df.groupby(df['id'].diff().ne(1.cumsum())['id'].transform('size')
它已经起作用了。非常感谢你们两位:)实际上我正在使用shift函数和group by
s = df['id'].diff().ne(1).cumsum()
df['count'] = s.map(s.value_counts())
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