【问题标题】:error unsupported operand type(s) for +: 'int' and 'method'+ 的错误不受支持的操作数类型:“int”和“method”
【发布时间】:2020-07-14 12:11:21
【问题描述】:

我的条形图有什么问题?
当我在这个 y 轴上使用变量名时,条形图不显示
y = [totalMales, totalFemales] # if I input numerical values it works, but it doesn't with variable names

#check total number of males
totalMales = newDF.loc[(newDF.Gender=='Male')].count #409
print("totalMales" + str(totalMales))


totalFemales = newDF.loc[(newDF.Gender=='Female')].count()  #77
print("totalFemales" + str(totalFemales))

#males are more likely to borrow than females 409 > 77

plt.style.use('ggplot')

x = ['Males', 'Females']
y = [totalMales, totalFemales]  # if I input numerical values it works, but it doesn't with variable names

x_pos = [i for i, _ in enumerate(x)]

plt.bar(x_pos, y, color='green')
plt.xlabel("Gender")
plt.ylabel("Total who Paid Off")
plt.title("Number of Males vs Females who Paid Off")

plt.xticks(x_pos, x)

plt.show()

【问题讨论】:

    标签: python-3.x pandas matplotlib


    【解决方案1】:

    count是一个方法,改成这个(totalFemale类似):

    totalMales = newDF.loc[(newDF.Gender=='Male'), 'Gender'].count()
    

    你也可以这样做:

    newDF.groupby('Gender').size().plot.bar()
    

    newDF['Gender'].value_counts().plot.bar()
    

    【讨论】:

    • 我检查了totalMalestotalFemale的类型是int64,那么count()有什么问题?
    • 我已经更正了,但现在我得到“形状不匹配:对象不能广播到单个形状” | https://gist.github.com/bibscy/5aa0d1cba753773bb88d1929a819309e
    • newDF.count() 返回一个 dtype 为 int64 的系列,而不是单个数字。请参阅totalMales 的更新。
    • 好的,totalMales = newDF.loc[(newDF.Gender=='Male'), 'Gender'].count() 在这个表达式中Gender 参数(在圆括号之后)的作用是什么?它映射到哪个字段?我知道newDF.loc[(newDF.Gender=='Male')newDF.Gender列中选择Male,但是第二个参数'Gnder]'的作用是什么
    • 第二个Gender 表示该列。所以该命令只选择一列(“性别”)进行计数。
    【解决方案2】:

    当您拥有 DataFrame 时,可以使用更多内置函数。使用value_counts,特定列中的不同值被计算并作为系列返回。使用.plot.bar() 这可以直接绘制在条形图中。 x-as 上的标签直接代表不同的性别。

        # Count the values
        gender_count = newDF.Gender.value_counts()
        
        # Create plot
        gender_count.plot.bar()
        
        # Settings for plot
        plt.style.use('ggplot')
        plt.xlabel("Gender")
        plt.ylabel("Total who Paid Off")
        plt.title("Number of Males vs Females who Paid Off")
        plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 2018-09-01
      • 2013-10-04
      • 2021-06-16
      相关资源
      最近更新 更多