【问题标题】:Barplot of two columns based on specific condition基于特定条件的两列条形图
【发布时间】:2022-01-15 05:56:18
【问题描述】:

我被分配了一项任务,我应该根据另一个列元素绘制一个元素。

代码如下:

# TODO: Plot the Male employee first name on 'Y' axis while Male salary is on 'X' axis
import pandas as pd 
import matplotlib.pyplot as plt 
data = pd.read_excel("C:\\users\\HP\\Documents\\Datascience task\\Employee.xlsx")

print(data.head(5))

输出:

    First Name  Last Name   Gender           Age    Experience (Years)  Salary
0   Arnold  Carter           Male             21                10    8344
1   Arthur  Farrell          Male             20                 7    6437
2   Richard Perry            Male             28                 3    8338
3   Ellia   Thomas           Female           26                 4    8870
4   Jacob   Kelly            Male             21                 4    548

如何绘制“性别”为男性的前 5 行的“名字”列与“工资”列。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    首先分别生成男性行,并提取名字和薪水进行绘图。

    以下代码识别前五名男性雇员,并将他们的名字和薪水转换为 x 和 y 列表。

    x = list(df[df['Gender'] == "Male"][:5]['Fname'])
    y = list(df[df['Gender'] == "Male"][:5]['Salary'])
    print(x)
    print(y)
    

    输出:

    ['Arnold', 'Arthur', 'Richard', 'Jacob']
    [8344, 6437, 8338, 548]
    

    请注意,df 中只有 4 个男性可用。

    然后我们可以根据需要绘制任何图表;

    plt.bar(x, y, color = ['r', 'g', 'b', 'y']);
    

    输出:

    【讨论】:

    • 它的工作方式和我想要的一样谢谢。但是'list()'有必要吗?
    【解决方案2】:

    seaborn 也可以提供帮助

    import seaborn as sns
    import matplotlib.plotly as plt
    
    sns.barplot( x=df[(df['Gender'] == "Male")]['First Name'][:5] , y = df[(df['Gender'] == "Male")]['Salary'][:5] )
    
    plt.xlabel('First Names')
    plt.ylabel('Salary')
    plt.title('Barplot of Male Employees')
    plt.show()
    
    

    【讨论】:

      猜你喜欢
      • 2018-07-23
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      • 2019-07-30
      • 1970-01-01
      相关资源
      最近更新 更多