簡體   English   中英

`groupby` 列未傳遞給 `apply` 函數。 Pandas 中可能存在的錯誤?

[英]`groupby` column not passed to `apply` function. Possible bug in Pandas?

GroupBy.apply (pandas 0.25.3) 中可能存在的錯誤:以下代碼通過class列創建groupby ,應用函數嘗試訪問class列。 代碼產生一個KeyError: 'class'異常:

import pandas as pd

df = pd.DataFrame(
    [
        ("bird", "Falconiformes", 389.0),
        ("bird", "Psittaciformes", 24.0),
        ("mammal", "Carnivora", 80.2),
        ("mammal", "Primates", 20),
        ("mammal", "Carnivora", 58),
    ],
    index=["falcon", "parrot", "lion", "monkey", "leopard"],
    columns=("class", "order", "max_speed"),
)

class_to_features = {"bird": ["wings", "feathers", "beak"], "mammal": ["udder"]}


def exec_groupby(df, _temp, c_2_f=None):
    def _helper(df):
        if c_2_f is not None:
            return c_2_f[df["class"].iloc[0]] + _temp # KeyError "class"
        else:
            return "goo" + _temp

    return df.groupby(["class"]).apply(lambda df: _helper(df))

print(exec_groupby(df, "foo"))
print(exec_groupby(df, "foo", class_to_features))

但是,如果我從return語句中刪除+ _temp它工作正常!

def exec_groupby(df, _temp, c_2_f=None):
    def _helper(df):
        if c_2_f is not None:
            return c_2_f[df["class"].iloc[0]] # Works fine! no errors
        else:
            return "goo" + _temp

    return df.groupby(["class"]).apply(lambda df: _helper(df))

似乎c_2_f的組合不是None並訪問導致異常的列。 我錯過了什么嗎?

錯誤日志讀取

TypeError: can only concatenate list (not "str") to list
...
During handling of the above exception, another exception occurred:
...
KeyError: 'class'

c_2_f鍵是列表,所以你不能將它與str連接起來

def exec_groupby(df, _temp, c_2_f=None):
    def _helper(df):
        if c_2_f is not None:
            return c_2_f[df["class"].iloc[0]] + [_temp] # Works fine! no errors
        else:
            return "goo" + _temp

    return df.groupby(["class"]).apply(lambda df: _helper(df))

這工作正常,並給出

class
bird      goofoo
mammal    goofoo
dtype: object
class
bird      [wings, feathers, beak, foo]
mammal                    [udder, foo]
dtype: object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM