Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.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 DataFrame列中重复值的顺序_Python_Pandas - Fatal编程技术网

Python DataFrame列中重复值的顺序

Python DataFrame列中重复值的顺序,python,pandas,Python,Pandas,如何在DataFrame中添加新列,该列将计算所有重复的值。在下面的示例中,我在be列中有3个来自865432的值,因此,作为输出,我添加列,并为此行填充值0、1和2 输入表 A B 0 865432 1 865432 2 134567 3 865432 4 134567 5 222222 输出表 A B C 0 865432 0 1 865432 1 3 865432 2 2 134567 0 4 134567 1 5 222222

如何在DataFrame中添加新列,该列将计算所有重复的值。在下面的示例中,我在be列中有3个来自
865432
的值,因此,作为输出,我添加列,并为此行填充值0、1和2

输入表

A       B
0  865432
1  865432
2  134567
3  865432
4  134567
5  222222
输出表

A       B  C
0  865432  0
1  865432  1
3  865432  2
2  134567  0
4  134567  1
5  222222  0
注意:订单和新列名不匹配

我知道如何在丑陋的循环和行操作中完成这项任务,但希望在pandas中有另一个更漂亮的解决方案。

您可以在“B”列中调用:


超级棒!非常感谢你
In [345]:

df['C'] = df.groupby('B', as_index=False)['B'].cumcount()
df
Out[345]:
   A       B  C
0  0  865432  0
1  1  865432  1
2  2  134567  0
3  3  865432  2
4  4  134567  1
5  5  222222  0