pandas 如何使用数据框组按不同范围绘制饼图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46542572/
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 04:34:27  来源:igfitidea点击:

How to plot pie chart using data frame group by different range?

pythonpandascsvmatplotlibdataframe

提问by Yash Singhvi

My Code is:

我的代码是:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style

df=pd.read_csv("patient1.csv")
a=df.loc[df.Age<18,['Age']]
print(a)
b=df.loc[(df.Age >= 18) & (df.Age < 60),['Age']]
print(b)
c=df.loc[df.Age>=60,['Age']]
print(c)
d=pd.concat([a,b,c],keys=["0-17","18-59","60+"])
e=d.loc[:,['Age']]
print(e)

The file patient1.csv contains data as:

文件patient1.csv 包含的数据如下:

Name    Surname Age
fdgf    bcbb    21
Yash    Singhvi 19
Yash    Singhvi 19
piyush  daga    20
cvcv    dfg     16
sdsd    sdsd    65
dsfef   fedf    12
rfef    fefe    70
fdgf    rgd     10

Actually, I want to plot pie chart of the patient of age 0-17,18-59,60+. From the code, you can see that I have separated the data frame in different ranges of age. What do I need to add to the code to plot the pie chart?

实际上,我想绘制年龄 0-17,18-59,60+ 的患者的饼图。从代码中可以看出,我已经将不同年龄范围的数据框分开了。我需要在代码中添加什么来绘制饼图?

回答by jezrael

You need cutfor create ranges first. Then groupby, aggregate sizeand reshape by unstack.

您首先需要cutcreate range。然后groupby,聚合size和重塑unstack

Last use DataFrame.plot.pie:

最后使用DataFrame.plot.pie

df['bins'] = pd.cut(df['Age'],bins=[0,17,59,120], labels=["0-17","18-59","60+"])
df = df.groupby(['Age', 'bins']).size().unstack(fill_value=0)
print (df)
bins  0-17  18-59  60+
Age                   
10       1      0    0
12       1      0    0
16       1      0    0
19       0      2    0
20       0      1    0
21       0      1    0
65       0      0    1
70       0      0    1

df.plot.pie(subplots=True,figsize=(8, 3))

graph

图形

EDIT:

编辑:

a = df.groupby('bins').size()
#a = df['bins'].value_counts()
print (a)
bins
0-17     3
18-59    4
60+      2
dtype: int64

a.plot.pie(figsize=(4,4))

graph

图形