Python + Pandas +数据可视化:如何获取每一行的百分比并可视化分类数据?

时间:2018-11-01 19:24:29

标签: python pandas matplotlib data-visualization crosstab

我正在对贷款预测数据集(Pandas数据框)进行探索性数据分析。该数据框有两列:Property_Area,其值分为三种类型:农村,城市,Semiurban。另一列是Loan_Status明智的值有两种类型:Y,N。我想绘制如下图:在X轴上应该有Property_Area,对于每种类型的3个区域,我想显示接受的贷款百分比或沿Y轴拒绝。该怎么做?

这是我的数据示例:

data = pd.DataFrame({'Loan_Status':['N','Y','Y','Y','Y','N','N','Y','N','Y','N'], 
       'Property_Area': ['Rural', 'Urban','Urban','Urban','Urban','Urban',
       'Semiurban','Urban','Semiurban','Rural','Semiurban']})

我尝试过:

status = data['Loan_Status']
index = data['Property_Area']
df = pd.DataFrame({'Loan Status' : status}, index=index)
ax = df.plot.bar(rot=0)

data is the dataframe for the original dataset

输出: enter image description here

编辑: 我能够做自己想做的事,但是为此,我必须编写一个长代码:

new_data = data[['Property_Area', 'Loan_Status']].copy()
count_rural_y = new_data[(new_data.Property_Area == 'Rural') & (data.Loan_Status == 'Y') ].count()
count_rural = new_data[(new_data.Property_Area == 'Rural')].count()
#print(count_rural[0])
#print(count_rural_y[0])
rural_y_percent = (count_rural_y[0]/count_rural[0])*100
#print(rural_y_percent)

#print("-"*50)

count_urban_y = new_data[(new_data.Property_Area == 'Urban') & (data.Loan_Status == 'Y') ].count()
count_urban = new_data[(new_data.Property_Area == 'Urban')].count()
#print(count_urban[0])
#print(count_urban_y[0])
urban_y_percent = (count_urban_y[0]/count_urban[0])*100
#print(urban_y_percent)

#print("-"*50)

count_semiurban_y = new_data[(new_data.Property_Area == 'Semiurban') & (data.Loan_Status == 'Y') ].count()
count_semiurban = new_data[(new_data.Property_Area == 'Semiurban')].count()
#print(count_semiurban[0])
#print(count_semiurban_y[0])
semiurban_y_percent = (count_semiurban_y[0]/count_semiurban[0])*100
#print(semiurban_y_percent)

#print("-"*50)

objects = ('Rural', 'Urban', 'Semiurban')
y_pos = np.arange(len(objects))
performance = [rural_y_percent,urban_y_percent,semiurban_y_percent]
plt.bar(y_pos, performance, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Loan Approval Percentage')
plt.title('Area Wise Loan Approval Percentage')

plt.show()

输出:

enter image description here

如果可以的话,能否请我建议一个更简单的方法?

1 个答案:

答案 0 :(得分:0)

带有Crosstabs的熊猫normalize将使这一过程变得简单

在pandas数据框中获取2列以上并为每行的百分比的一种简单方法是将pandas crosstab函数与normalize = 'index'一起使用< / p>


交叉表函数的查找方式如下:

# Crosstab with "normalize = 'index'". 
df_percent = pd.crosstab(data.Property_Area,data.Loan_Status,
                         normalize = 'index').rename_axis(None)

# Multiply all percentages by 100 for graphing. 
df_percent *= 100

这将输出df_percent,看起来像这样:

Loan_Status          N          Y
Rural        50.000000  50.000000
Semiurban    66.666667  33.333333
Urban        16.666667  83.333333

然后,您可以非常轻松地将其绘制到条形图中:

# Plot only approvals as bar graph. 
plt.bar(df_percent.index, df_percent.Y, align='center', alpha=0.5)
plt.ylabel('Loan Approval Percentage')
plt.title('Area Wise Loan Approval Percentage')

plt.show()

并获得结果图表:

Matplotlib bar plot from pandas crosstab

Here you can see the code working in google colab


这是我为此答案生成的示例数据框:

data = pd.DataFrame({'Loan_Status':['N','Y','Y','Y','Y','N','N','Y','N','Y','Y'
   ], 'Property_Area': ['Rural', 'Urban','Urban','Urban','Urban','Urban',
   'Semiurban','Urban','Semiurban','Rural','Semiurban']})

创建此示例数据框:

   Loan_Status Property_Area
0            N         Rural
1            Y         Urban
2            Y         Urban
3            Y         Urban
4            Y         Urban
5            N         Urban
6            N     Semiurban
7            Y         Urban
8            N     Semiurban
9            Y         Rural
10           Y     Semiurban