本文介绍了如何在图表中绘制 pandas groupby值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件,其中包含性别"和婚姻状况"以及下面的其他几列.

I have a csv file which contains Gender and Marriage status along with few more columns like below.

Loan_ID,Gender,Married,Dependents,Education,Self_Employed,ApplicantIncome,CoapplicantIncome,LoanAmount,Loan_Amount_Term,Credit_History,Property_Area,Loan_Status
LP001002,Male,No,0,Graduate,No,5849,0,,360,1,Urban,Y
LP001003,Male,Yes,1,Graduate,No,4583,1508,128,360,1,Rural,N
LP001005,Male,Yes,0,Graduate,Yes,3000,0,66,360,1,Urban,Y
LP001006,Male,Yes,0,Not Graduate,No,2583,2358,120,360,1,Urban,Y
LP001008,Male,No,0,Graduate,No,6000,0,141,360,1,Urban,Y
LP001011,Male,Yes,2,Graduate,Yes,5417,4196,267,360,1,Urban,Y

我想数一数.的已婚男性和女性的比例,并在图表中显示如下所示

I want to count no. of married Males and Females and show the same in graph as shown below

下面是我正在使用的代码:

Below is the code I am using :

import csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    x=[]
    y=[]
    df = pd.read_csv(
        "/home/train.csv",usecols=[1,2]).dropna(subset=['Gender','Married'])  # Reading the dataset in a dataframe using Pandas
    groups = df.groupby(['Gender','Married'])['Married'].apply(lambda x: x.count())
    print(groups)

分组之后,我得到以下结果:

After group by I have following result :

Gender  Married
Female  No          80
        Yes         31
Male    No         130
        Yes        357

我想要一个类似下面的图表

I want a chart like below

推荐答案

您可以使用 groupby + size ,然后使用 Series.plot.bar :

You can use groupby + size and then use Series.plot.bar:

计数与大小之间的差异

groups = df.groupby(['Gender','Married']).size()
groups.plot.bar()

另一种解决方案是添加 unstack 重塑形状或 crosstab :

Another solution is add unstack for reshape or crosstab:

print (df.groupby(['Gender','Married']).size().unstack(fill_value=0))
Married   No  Yes
Gender
Female    80   31
Male     130  357

df.groupby(['Gender','Married']).size().unstack(fill_value=0).plot.bar()

或者:

pd.crosstab(df['Gender'],df['Married']).plot.bar()

这篇关于如何在图表中绘制 pandas groupby值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 13:43