计算某个值在数据帧列中出现的频率 [英] Count the frequency that a value occurs in a dataframe column
本文介绍了计算某个值在数据帧列中出现的频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据集
category
cat a
cat b
cat a
我希望能够返回类似(显示唯一值和频率)
I'd like to be able to return something like (showing unique values and frequency)
category freq
cat a 2
cat b 1
推荐答案
使用groupby
和count
:
In [37]:
df = pd.DataFrame({'a':list('abssbab')})
df.groupby('a').count()
Out[37]:
a
a
a 2
b 3
s 2
[3 rows x 1 columns]
查看在线文档:https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html
还有 value_counts()
正如@DSM 所评论的,这里有很多给猫剥皮的方法
Also value_counts()
as @DSM has commented, many ways to skin a cat here
In [38]:
df['a'].value_counts()
Out[38]:
b 3
a 2
s 2
dtype: int64
如果您想将频率添加回原始数据帧,请使用 transform
返回对齐的索引:
If you wanted to add frequency back to the original dataframe use transform
to return an aligned index:
In [41]:
df['freq'] = df.groupby('a')['a'].transform('count')
df
Out[41]:
a freq
0 a 2
1 b 3
2 s 2
3 s 2
4 b 3
5 a 2
6 b 3
[7 rows x 2 columns]
这篇关于计算某个值在数据帧列中出现的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文