seaborn 的人口金字塔 python

Population pyramid with seaborn python

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().

我认为您的问题来自 order=AgeClass SeaBorn 期望存在于 table 中的值数组,而不是范围字符串。

我无权访问您的数据集,所以我不确定。 据我所知,一个问题可能是您传递给 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'")