在 Pandas 数据框中创建 value_counts 列 [英] Create column of value_counts in Pandas dataframe

查看:100
本文介绍了在 Pandas 数据框中创建 value_counts 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的 Pandas 数据框列之一创建唯一值的计数,然后将包含这些计数的新列添加到我的原始数据框中.我尝试了几种不同的方法.我创建了一个熊猫系列,然后使用 value_counts 方法计算了计数.我试图将这些值合并回我的原始数据帧,但我想合并的键在索引(ix/loc)中.

I want to create a count of unique values from one of my Pandas dataframe columns and then add a new column with those counts to my original data frame. I've tried a couple different things. I created a pandas series and then calculated counts with the value_counts method. I tried to merge these values back to my original dataframe, but I the keys that I want to merge on are in the Index(ix/loc).

Color Value
Red   100
Red   150
Blue  50

我想返回如下内容:

Color Value Counts
Red   100   2
Red   150   2 
Blue  50    1

推荐答案

df['Counts'] = df.groupby(['Color'])['Value'].transform('count')

例如

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

请注意,transform('count') 会忽略 NaN.如果要计算 NaN,请使用 transform(len).

Note that transform('count') ignores NaNs. If you want to count NaNs, use transform(len).

致匿名如果您在使用 transform('count') 时遇到错误,可能是因为您的 Pandas 版本太旧.以上适用于 0.15 或更高版本的 Pandas.

To the anonymous editor: If you are getting an error while using transform('count') it may be due to your version of Pandas being too old. The above works with pandas version 0.15 or newer.

这篇关于在 Pandas 数据框中创建 value_counts 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆