【问题标题】:Population pyramid with seaborn python [duplicate]带有seaborn python的人口金字塔[重复]
【发布时间】:2022-01-12 18:39:52
【问题描述】:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

Female = df[(df["Gender"] == "Female")]
Male = df[(df["Gender"] == "Male")]

AgeClass = ['100+','95-99','90-94','85-89','80-84','75-79','70-74','65-69','60-64','55-59','50-54','45-49','40-44','35-39','30-34','25-29','20-24','15-19','10-14','5-9','0-4']

bar_plot = sns.barplot(x= Male, y=df['Age'], order=AgeClass)

bar_plot = sns.barplot(x= Female, y=df['Age'], order=AgeClass)

bar_plot.set(xlabel="Population (hundreds of millions)", ylabel="Age-Group", title = "Population Pyramid")

我正在尝试使用 seaborn 从 pandas df 构建人口金字塔。

我得到了值错误。帮我解决它

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

【问题讨论】:

    标签: python seaborn


    【解决方案1】:

    我无权访问您的数据集,所以我不确定。 据我所知,一个问题可能是您传递给 y 的系列与您传递给 x 的系列的大小不同,因为 x 是掩码的结果,而 y 是来自整个原始 DataFrame 的系列。

    你应该这样做:

    mask_female = df["Gender"] == "Female"
    female = df[mask_female]["Gender"]
    age_female = df[mask_female]["Age"]
    
    mask_male = df["Gender"] == "Male"
    male = df[mask_male]["Gender"]
    age_male = df[mask_male]["Age"]
    

    然后,对于sns.barplot 调用,您应该将maleage_malefemaleage_female 传递给x 和y 参数。

    此外,请确保 AgeClass 中的所有值都实际存在于“年龄”列中。

    一个小建议:在创建这样的掩码时,我会使用非常漂亮且可读的eval 方法:

    mask_male = df.eval("Gender == 'Male'")
    

    【讨论】:

      【解决方案2】:

      我相信您的问题来自order=AgeClass SeaBorn 期望表中存在一个值数组,而不是范围字符串。

      【讨论】:

        猜你喜欢
        • 2020-12-16
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 2015-11-01
        • 2019-09-24
        • 2013-03-26
        • 1970-01-01
        相关资源
        最近更新 更多