熊猫groupby两列和图

时间:2019-01-01 18:23:59

标签: python pandas

我有一个这样的数据框:

app.get('/api/timestamp/:date', (req,res) => {

  let date = new Date(req.params.date);
  if (req.params.date && date instanceOf Date) {
    let unix = date.getTime();  
    let utc = date.toUTCString();
    res.send({unix, utc}); 
  } else {
    res.send({'error': 'Invalid Date'});
  }
}

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

我尝试过:
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')})

但这给出了: enter image description here

如何获取每个类别的性别计数?

3 个答案:

答案 0 :(得分:5)

IIUC,

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

enter image description here

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

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

答案 1 :(得分:3)

使用groupby + unstack:

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

使用数据透视表:

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

使用seaborn:

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

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

输出

enter image description here

答案 2 :(得分:1)

您也可以使用此

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

结果完全相同。

enter image description here

相关问题