In [102]: df = pd.DataFrame({'Color': 'Red Red Blue'.split(), 'Value': [100, 150, 50]})
In [103]: df
Out[103]:
Color Value
0 Red 100
1 Red 150
2 Blue 50
In [104]: df['Counts'] = df.groupby(['Color'])['Value'].transform('count')
In [105]: df
Out[105]:
Color Value Counts
0 Red 100 2
1 Red 150 2
2 Blue 50 1
这个答案使用^{} 和^{} 。用熊猫1.1进行了测试
信贷:comment由sacuL
比如说,
注意
transform('count')
忽略了NAN。如果要计算NAN,请使用transform(len)
匿名编辑:如果您在使用
transform('count')
时出现错误,可能是因为您的Pandas版本太旧。以上内容适用于pandas版本0.15或更高版本另一个选择:
此选项将为您提供一列,其中包含重复的计数值,对应于“颜色”列中每个值的频率
相关问题 更多 >
编程相关推荐