gpt4 book ai didi

带有 IntEnum 的 pandas value_counts() 引发 RecursionError

转载 作者:行者123 更新时间:2023-12-05 07:13:57 25 4
gpt4 key购买 nike

我得到了以下代码来详细说明我的问题。我正在使用 python 3.6 和 pandas==0.25.3。

import pandas as pd
from enum import Enum, IntEnum


class BookType(Enum):
DRAMA = 5
ROMAN = 3


class AuthorType(IntEnum):
UNKNOWN = 0
GROUP = 1
MAN = 2


def print_num_type(df: pd.DataFrame, col_name: str, enum_type: Enum) -> int:
counts = df[col_name].value_counts()
val = counts[enum_type]
print('value counts:', counts)
print(f'Found "{val}" of type {enum_type}')


d = {'title': ['Charly Morry', 'James', 'Watson', 'Marry L.'], 'isbn': [21412412, 334764712, 12471021, 124141111], 'book_type': [BookType.DRAMA, BookType.ROMAN, BookType.ROMAN, BookType.ROMAN], 'author_type': [AuthorType.UNKNOWN, AuthorType.UNKNOWN, AuthorType.MAN, AuthorType.UNKNOWN]}
df = pd.DataFrame(data=d)
df.set_index(['title', 'isbn'], inplace=True)
df['book_type'] = df['book_type'].astype('category')
df['author_type'] = df['author_type'].astype('category')

print(df)
print(df.dtypes)

print_num_type(df, 'book_type', BookType.DRAMA)
print_num_type(df, 'author_type', AuthorType.UNKNOWN)

我的 pandas.DataFramecategorical 类型的两列(book_typeauthor_type)组成。此外,book_type 是一个继承自类型Enumauthor_type 的类,继承自IntEnum。当调用 print_num_type(df, 'book_type', BookType.DRAMA) 时,一切都按预期进行,并且打印了这种类型的书籍数量,而 print_num_type(df, 'author_type', AuthorType .UNKNOWN) 引发错误:

Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\abc.py", line 182, in __instancecheck__
if subclass in cls._abc_cache:
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\_weakrefset.py", line 72, in __contains__
wr = ref(item)
RecursionError: maximum recursion depth exceeded while calling a Python object
Exception ignored in: 'pandas._libs.lib.c_is_list_like'
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\abc.py", line 182, in __instancecheck__
if subclass in cls._abc_cache:
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\_weakrefset.py", line 72, in __contains__
wr = ref(item)
RecursionError: maximum recursion depth exceeded while calling a Python object

我在这里做错了什么?是否有解决此错误的解决方法?因为我无法更改 AuthorTypeIntEnum 类型,因为它是从另一个库提供的。

提前致谢!

最佳答案

查看答案 here

主要思想是因为你函数中的x.value_counts()counts本身就是一个pandas Series,所以最好使用.iat.iloc 调用它时,例如 see iat docs

我认为最简单的解决方案是只使用 (x==0).sum(),或者在您的语法中:

val = (df[col_name]==enum_type).sum()

我在您问题下的评论中放了一个最小的工作示例,以便您可以使用“x”符号轻松重现问题/修复。

关于带有 IntEnum 的 pandas value_counts() 引发 RecursionError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60026689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com