我想在我的 pandas 数据框中创建一列value_counts [英] I want to create a column of value_counts in my pandas dataframe
问题描述
我对R更熟悉,但我想看看是否有办法在熊猫中做到这一点.我想从我的一个数据框列中创建一个唯一值计数,然后将具有这些计数的新列添加到我的原始数据框中.我尝试了几种不同的方法.我创建了一个熊猫系列,然后使用value_counts方法计算了计数.我试图将这些值合并回我的原始数据帧,但是我要合并的键在Index(ix/loc)中.任何建议或解决方案将不胜感激
I am more familiar with R but I wanted to see if there was a way to do this in pandas. I want to create a count of unique values from one of my 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). Any suggestions or solutions would be appreciated
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或更高版本的熊猫.
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屋!