【问题标题】:Plot distribution of pandas dataframe depending on target value根据目标值绘制 pandas 数据帧的分布
【发布时间】:2021-09-04 20:20:45
【问题描述】:

我想根据sex(男/女)可视化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');

【问题讨论】:

    标签: python dataframe plot seaborn histogram


    【解决方案1】:

    你可以在 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()
    

    【讨论】:

    • 这条线x=df.loc['sex'==1, 'grade']给了我KeyError: False
    猜你喜欢
    • 2018-05-05
    • 2016-07-11
    • 2020-12-23
    • 2021-04-29
    • 2019-07-14
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多