我有一个数据集
category
cat a
cat b
cat a
我希望能够返回如下内容(显示唯一的值和频率)
category freq
cat a 2
cat b 1
发布于 2014-03-14 05:41:34
使用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
还有@DSM评论的value_counts()
,这里有很多种剥猫皮的方法。
In [38]:
df['a'].value_counts()
Out[38]:
b 3
a 2
s 2
dtype: int64
如果您希望将频率添加回原始数据帧,请使用transform
返回对齐的索引:
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]
发布于 2016-04-06 02:30:11
如果要应用于所有列,可以使用:
df.apply(pd.value_counts)
这将对每一列应用一个基于列的聚合函数(在本例中为value_counts)。
发布于 2018-01-16 01:52:11
df.category.value_counts()
这一小段代码将为您提供所需的输出。
如果您的列名包含空格,则可以使用
df['category'].value_counts()
https://stackoverflow.com/questions/22391433
复制相似问题