【问题标题】:seaborn dataframe question in python to groupby and countpython中的seaborn数据框问题到groupby和count
【发布时间】:2021-01-30 12:04:15
【问题描述】:

我的 Python 数据框中有这些数据。第二列是性别,第三列是汽车品牌。 我想按总数计算排名前五的汽车品牌。对于前五名品牌,我将需要 seaborn 图来进行基于性别的品牌计数。 IE。多少男,多少女。

# This prints all the brands. But I need only the top 5 though. 
sns.countplot(x = 'brand', hue = 'gender', data = dfCarBrand, palette = 'magma')
plt.show()

有什么建议吗?

Data
1   F   Ford
2   M   BMW
3   F   Skoda
4   M   GM
5   M   Audi
6   F   Audi
7   M   Mitsubishi
8   M   Hyundai
9   M   Honda
10  F   Renault
11  F   Renault
12  F   Audi
13  F   Skoda
14  M   GM
15  F   Audi
16  M   Audi
17  M   Mitsubishi
18  M   Hyundai
19  M   Honda
20  F   Renault
21  M   Renault
22  M   Audi
23  M   Skoda
24  M   BMW
25  F   Skoda
26  M   GM
27  M   Audi
28  M   Audi
29  F   Mitsubishi
30  F   Hyundai
31  M   Honda
32  F   Skoda
33  M   GM
34  M   Audi
35  M   Skoda
36  M   BMW
37  F   Skoda
38  F   Audi
39  F   Skoda
40  M   GM

【问题讨论】:

    标签: python dataframe seaborn


    【解决方案1】:

    由于无法指定图表中的前 5 个,我们将处理要在图表中使用的数据。以value_counts()获取品牌的频数,并将结果列为前5的系列索引。

    import seaborn as sns
    import matplotlib.pyplot as plt
    import pandas as pd
    
    dfCarBrand5 = dfCarBrand[dfCarBrand['brand'].isin(dfCarBrand.brand.value_counts().head(5).index.tolist())]
    sns.countplot(x='brand', hue='gender', data=dfCarBrand5, palette='magma')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 1970-01-01
      • 2021-08-14
      • 2022-01-14
      • 2017-09-13
      • 2016-05-12
      • 2018-07-16
      • 2012-06-24
      • 2021-12-18
      相关资源
      最近更新 更多