根据目标值绘制 pandas 数据帧的分布图

Plot distribution of pandas dataframe depending on target value

我想根据 sex (male/female) 可视化 grade

我的数据框:

df = pd.DataFrame(
 {
 "key": ["K0", "K1", "K2", "K3", "K4", "K5", "K6", "K7", "K8", "K9"],
 "grade": [1.0, 2.0, 4.0, 1.0, 5.0, 2.0, 3.0, 1.0, 6.0, 3.0],
 "sex": [1, 0, 0, 1, 0,1,0,1,0,0] 
 }
)


    key grade   sex
0   K0   1.0     1
1   K1   2.0     0
2   K2   4.0     0
3   K3   1.0     1
4   K4   5.0     0
5   K5   2.0     1
6   K6   3.0     0
7   K7   1.0     1
8   K8   6.0     0
9   K9   3.0     0

我的方法是使用直方图并绘制分布图。但是,我不知道如何根据目标可视化分布。 Seaborn Documentation 中有一些示例,但我未能将其应用到我的具体问题中。

我只有这个:

plt.hist(df['grade'], bins=10, edgecolor='black');
plt.xlabel('grade');
plt.ylabel('count');

您可以在 matplotlib 中执行此操作:

import matplotlib.pyplot as pyplot

x=df.loc[df['sex']==1, 'grade']
y=df.loc[df['sex']==0, 'grade']

bins=list(range(6))

pyplot.hist(x, bins, alpha=0.5, label='sex=1')
pyplot.hist(y, bins, alpha=0.5, label='sex=2')
pyplot.legend(loc='upper right')
pyplot.show()

还有一种方法可以用 pandas:

df[df['sex'] == 0]['grade'].plot.hist()
df[df['sex'] == 1]['grade'].plot.hist()

您还可以使用 kde():

获得平滑的曲线
df[df['sex'] == 0]['grade'].plot.kde()