2017-07-25 441 views
1

我有一個csv文件,其中包含Gender和Marriage狀態以及下面的更多列。如何在圖中繪製pandas groupby值?

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 

我想計數沒有。已婚男性和女性,並顯示在圖中相同的如下圖所示

下面是我使用的代碼:

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) 

組後我有以下結果:

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

我想像下面

enter image description here

+0

您需要更具體地瞭解您遇到的問題。 –

+0

只是瀏覽優秀的[熊貓文檔](https://pandas.pydata.org/pandas-docs/stable/visualization.html) – Quickbeam2k1

+0

@AndrewL我想有一個圖表沒有。的已婚男性和女性。使用DF我可以groupby和計數已婚男女。我想代表相同的使用python圖表 – pythonaddict

回答

4

你能給我們一個圖表e groupby + size然後使用Series.plot.bar

Difference between count and size

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

graph

另一種解決方案是增加unstack的重塑或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() 

graph

+0

你使用spyder/anaconda? – jezrael

+0

但我想你可以先使用'import matplotlib.pyplot as plt',然後使用'df.groupby(['Gender','Married'])。size()。unstack(fill_value = 0).plot.bar( )'和最後'plt.show()' – jezrael

+1

感謝它解決了! :) - @jezrael – pythonaddict