【发布时间】:2018-11-01 19:24:29
【问题描述】:
我正在对贷款预测数据集(Pandas 数据框)进行探索性数据分析。此数据框有两列:Property_Area,其值为三种类型 - Rural、Urban、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
编辑: 我能够做我想做的事,但为此我不得不写一段很长的代码:
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()
输出:
如果可能的话,您能否建议我一个更简单的方法?
【问题讨论】:
-
当您说“它不起作用”时,您是什么意思?错误?看起来不像你想要的?请给我们多一点继续。您能否提供一些样本或虚拟数据以及您目前绘制的图片?
-
已编辑。请看。
-
您能否提供一些示例数据。正如@G.Anderson 也指出的那样,给定的信息不足以重现该问题。
-
感谢您添加示例数据。我会首先将数据作为多列引入,然后执行 `groupby('Property_Area').count()' 来获取您的实际值计数,然后尝试绘制
-
关于您的编辑,我很高兴您能够解决它。这个答案Pandas percentage of total with groupby 提供了一个基于总数百分比创建聚合列的快速概述。这可能会给你更简单的代码。
标签: python pandas matplotlib data-visualization crosstab