在数据框中创建值_计数列

2024-04-25 19:59:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Color Value
Red   100
Red   150
Blue  50

我想退货,比如:

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

Tags: 数据方法原始数据valueblueredloccolor
3条回答

这个答案使用^{}^{}。用熊猫1.1进行了测试

df['counts'] = df['attribute'].map(df['attribute'].value_counts())

信贷:commentsacuL

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)


匿名编辑:如果您在使用transform('count')时出现错误,可能是因为您的Pandas版本太旧。以上内容适用于pandas版本0.15或更高版本

另一个选择:

z = df['Color'].value_counts 

z1 = z.to_dict() #converts to dictionary

df['Count_Column'] = df['Color'].map(z1) 

此选项将为您提供一列,其中包含重复的计数值,对应于“颜色”列中每个值的频率

相关问题 更多 >