Reputation: 61
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:
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?
Upvotes: 6
Views: 33449
Reputation: 862681
You need cut
for create range
s first. Then groupby
, aggregate size
and reshape by unstack
.
Last use 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))
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))
Upvotes: 14