Pandas 从 1.5.3 升级到 2.1 即使密钥确实存在,也会在 df.sum() 上返回密钥错误

问题描述 投票:0回答:1

我最近将 pandas 1.5.3 升级到 2.1。我没有更改任何代码,下面给出的先前运行良好的 df.["Total"].sum() 现在返回单词“Total”上的关键错误,即使该键确实存在并且在 1.5 上运行良好。 3.

感谢在版本之间更改时遇到的任何已知问题。

我尝试检查代码在 1.5.3 上运行良好,仅在升级到 >2.0 时失败。 我已经检查了键“Total”确实存在并且拼写正确。

acount = stat_not_on_conject_latest_rev["Total"].sum() + stat_not_on_conject_not_latest_rev["Total"].sum()

stat_not_on_conject_not_latest_rev 返回下面的 DF

        Type    Total
0   Drawings    118
1   Reports 8
2   Specifications  2
3   Contractor Submittals   2

stat_not_on_conject_latest_rev 返回下面的 DF

        Type    Total
0   Drawings    65

acount 正确返回值 195

我已经弄清楚为什么会出现关键错误。当运行完全相同的代码但使用 pandas 2.1 时,DF 会以完全不同的列名返回。 我不知道这是为什么?

stat_not_on_conject_latest_rev 返回下面的 DF

fapcount    count
0   Drawings    65

stat_not_on_conject_not_latest_rev 返回下面的 DF

    concount    count
0   Drawings    118
1   Reports 8
2   Specifications  2
3   Contractor Submittals   2

问题似乎是 Pandas 2.1 没有像 1.5.3 那样重命名列。在创建 DF 的代码下面,调用下面给出的“表函数”;

stat_not_on_conject_latest_rev = table(df,'fapcount')
stat_not_on_conject_not_latest_rev = table(df,'concount')

def table(df,col):
    table = df[col].value_counts().to_frame()
    table = table.rename(columns={col: "Total"})
    table = table.reset_index()
    table = table.rename(columns={"index": "Type"})
    return table

df 源自 CSV 文件导入;

df = pd.read_csv(filereads, skiprows=1)
pandas keyerror
1个回答
0
投票

这是由于函数

value_counts_internal
返回
2.1.0
一个命名系列。

def value_counts_internal(
    values,
    sort: bool = True,
    ascending: bool = False,
    normalize: bool = False,
    bins=None,
    dropna: bool = True,
) -> Series:
    from pandas import (
        Index,
        Series,
    )

    index_name = getattr(values, "name", None)
    name = "proportion" if normalize else "count"
    ...

让我们考虑下面的例子:

df = pd.DataFrame({
    "fapcount": [1, 2, 2, 3, 3], "concount": [3, 4, 4, 5, 5]
})

1.5.3
,我们得到:

>>> df["fapcount"].value_counts()

2    2
3    2
1    1
Name: fapcount, dtype: int64

虽然,截至目前

2.1.0
,该系列有一个名称
"count"
,并且列名称成为索引名称:

>>> df["fapcount"].value_counts()

fapcount
2    2
3    2
1    1
Name: count, dtype: int64 # <-- look at the name here !

>>> df["fapcount"].value_counts().index
Index([2, 3, 1], dtype='int64', name='fapcount')

所以,为了解决你的问题,你可以稍微调整你的功能

table

def table(df, col):
    return (
        df[col].value_counts()
            .rename_axis("Type")
            .reset_index(name="Total")
    )
© www.soinside.com 2019 - 2024. All rights reserved.