Pandas groupby 两列并绘制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53997862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:14:37  来源:igfitidea点击:

Pandas groupby two columns and plot

pythonpandas

提问by astro123

I have a dataframe like this:

我有一个这样的数据框:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.DataFrame({'category': list('XYZXY'), 'B': range(5,10),'sex': list('mfmff')})

I want to plot count of sex male or female based on category from column 'category'.

我想根据“类别”列中的类别绘制性别男性或女性的计数。

I tried:
df.groupby(['category','sex'])['category','sex'].count().plot.bar()

我试过:
df.groupby(['category','sex'])['category','sex'].count().plot.bar()

But this gives: enter image description here

但这给出了: 在此处输入图片说明

How to get the count of sex per category?

如何获得每个类别的性别数?

采纳答案by Poudel

Using groupby+unstack:

使用 groupby+unstack:

df.groupby(['sex','category'])['B'].count().unstack('sex').plot.bar()

Using pivot_table:

使用pivot_table:

pd.pivot_table(df, values = 'B', index = 'category',
               columns = 'sex',aggfunc ='count').plot.bar()

Using seaborn:

使用seaborn:

import seaborn as sns
sns.countplot(data=df,x='category',hue='sex')

or,
sns.catplot(data=df,kind='count',x='category',hue='sex')

output

输出

enter image description here

在此处输入图片说明

回答by Vaishali

IIUC,

国际大学联盟,

df.groupby(['category','sex']).B.count().unstack().reset_index()\
.plot.bar(x = 'category', y = ['f', 'm'])

enter image description here

在此处输入图片说明

Edit: If you have multiple columns, you can use groupby, count and droplevel.

编辑:如果您有多个列,则可以使用 groupby、count 和 droplevel。

new_df = df.groupby(['category','sex']).count().unstack()
new_df.columns = new_df.columns.droplevel()
new_df.reset_index().plot.bar()

回答by plasmon360

You can also use this

你也可以用这个

pd.pivot_table(df, values = 'B', index = 'category', columns = 'sex',
               aggfunc = lambda x: len(x)).plot.bar()

which results in exactly the same plot.

这导致完全相同的情节。

enter image description here

在此处输入图片说明