如何在图表中绘制 pandas 的分组值

2024-08-22Python开发问题
5

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

问题描述

我有一个CSV文件,其中包含性别和婚姻状况,以及一些类似下面的列。

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)

在GROUP BY I之后,结果如下:

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

我想要以下图表

推荐答案

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

Difference between count and size。

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

另一个解决方案是添加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()

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

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10