【问题标题】:How can I get the percentage of missing in a column using agg function?如何使用 agg 函数获取列中缺失的百分比?
【发布时间】:2021-01-22 06:51:42
【问题描述】:

我正在使用数据集 database_versao_LatLongDecimal_fonteANM_23_01_2019.csv - 你可以在这里找到它https://www.kaggle.com/edumagalhaes/brazilian-dams-and-brumadinho-households - 我希望在“CATEGORIA_DE_RISCO”列中找到缺失的百分比,按 UF 分组。

这是我尝试过的:

summary = (
    base_1.groupby(["UF"], sort=False)
    .agg(
        media=("Dano_Potencial__Alta", "count"),
        minimo=("Dano_Potencial__Alta", "mean"),
        Missing_Risco=(
            "CATEGORIA_DE_RISCO",
            lambda x: x.CATEGORIA_DE_RISCO.isnull().sum() / len(x),
        )
    )
    .reset_index()
    .round(1)
)

summary

但我不断收到错误消息:

AttributeError: 'Series' object has no attribute 'CATEGORIA_DE_RISCO'

我了解该错误,但我不确定它为什么会发生以及如何解决它。我确信我会在这里找到一些答案,但我只发现了如何丢失一列以及如何获得某个值的百分比。这很奇怪,因为我使用了与帖子Aggregate groups in Python Pandas and spit out percentage from a certain count 的答案类似的逻辑。

【问题讨论】:

    标签: python pandas dataframe aggregate-functions


    【解决方案1】:

    删除列名并改为将sum除以长度使用mean

    summary = (
        base_1.groupby(["UF"], sort=False)
        .agg(
            media=("Dano_Potencial__Alta", "count"),
            minimo=("Dano_Potencial__Alta", "mean"),
            Missing_Risco=(
                "CATEGORIA_DE_RISCO",
                lambda x: x.isnull().mean(),
            )
        )
        .reset_index()
        .round(1)
    )
    

    辅助列的另一个想法:

    summary = (
        base_1.assign(null_col = base_1['CATEGORIA_DE_RISCO'].isnull())
        .groupby(["UF"], sort=False)
        .agg(
            media=("Dano_Potencial__Alta", "count"),
            minimo=("Dano_Potencial__Alta", "mean"),
            Missing_Risco=("null_col",'mean')
        )
        .reset_index()
        .round(1)
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-28
      • 2022-08-23
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 2021-11-12
      • 2022-06-28
      • 1970-01-01
      相关资源
      最近更新 更多