如何对行进行分组,以便在使用 pandas 创建的组上使用value_counts? [英] How to group rows so as to use value_counts on the created groups with pandas?
本文介绍了如何对行进行分组,以便在使用 pandas 创建的组上使用value_counts?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在数据框中有这样的客户数据:
I have some customer data such as this in a data frame:
S No Country Sex
1 Spain M
2 Norway F
3 Mexico M
...
我想要这样的输出:
Spain
M = 1207
F = 230
Norway
M = 33
F = 102
...
我有一个基本概念,我想根据他们所在的国家/地区对行进行分组,例如 df.groupby(df.Country)
,并且在选定的行上,我需要运行类似 df.Sex.value_counts()
I have a basic notion that I want to group my rows based on their countries with something like df.groupby(df.Country)
, and on the selected rows, I need to run something like df.Sex.value_counts()
谢谢!
推荐答案
我认为需要 交叉表
:
I think need crosstab
:
df = pd.crosstab(df.Sex, df.Country)
或者如果要使用您的解决方案,请添加 unstack
用于具有第一级的列 MultiIndex
的值:
Or if want use your solution add unstack
for columns with first level of MultiIndex
:
df = df.groupby(df.Country).Sex.value_counts().unstack(level=0, fill_value=0)
print (df)
Country Mexico Norway Spain
Sex
F 0 1 0
M 1 0 1
编辑:
如果要添加更多列,则可以设置将哪个级别参数转换为列:
If want add more columns then is possible set which level parameter is converted to columns:
df1 = df.groupby([df.No, df.Country]).Sex.value_counts().unstack(level=0, fill_value=0).reset_index()
print (df1)
No Country Sex 1 2 3
0 Mexico M 0 0 1
1 Norway F 0 1 0
2 Spain M 1 0 0
df2 = df.groupby([df.No, df.Country]).Sex.value_counts().unstack(level=1, fill_value=0).reset_index()
print (df2)
Country No Sex Mexico Norway Spain
0 1 M 0 0 1
1 2 F 0 1 0
2 3 M 1 0 0
df2 = df.groupby([df.No, df.Country]).Sex.value_counts().unstack(level=2, fill_value=0).reset_index()
print (df2)
Sex No Country F M
0 1 Spain 0 1
1 2 Norway 1 0
2 3 Mexico 0 1
这篇关于如何对行进行分组,以便在使用 pandas 创建的组上使用value_counts?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文