pandas 计算列中的元素并以重复的方式显示 [英] Pandas count elements in a columns and show in duplicated way
本文介绍了 pandas 计算列中的元素并以重复的方式显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想得到这样的东西。
A
1
1
2
3
3
4
4
4
4
我要使其成为
A B
1 2
1 2
2 1
3 2
3 2
4 4
4 4
4 4
4 4
就像您在这里看到的那样,密钥是重复的,并且仍然与原始顺序相同。
Like you see here, the keys are duplicated and still in the same order as original.
我知道如何通过使用data.table在R中完成此任务,我只知道如何使用groupby来获取熊猫中唯一的键计数。
I know how to do this task in R by using data.table and I only know how to use groupby to get unique key counts in pandas.
有人有想法吗?
谢谢!
推荐答案
您可以使用以下命令:
import pandas as pd
df = pd.DataFrame({
'A' : [1, 1, 2, 3, 3, 4, 4, 4, 4]
})
df['B'] = df.groupby(['A'])['A'].transform('count')
print(df)
输出:
A B
0 1 2
1 1 2
2 2 1
3 3 2
4 3 2
5 4 4
6 4 4
7 4 4
8 4 4
这篇关于 pandas 计算列中的元素并以重复的方式显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文