Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: np.where may not preserve Enum type when used with a mix of Enums defined using a custom class that inherits from both str and Enum #23423

Closed
luke396 opened this issue Mar 18, 2023 · 2 comments
Labels

Comments

@luke396
Copy link

luke396 commented Mar 18, 2023

Describe the issue:

Hi, when using the np.where function with an array of Enums defined using a custom class that inherits from both str and Enum, the resulting array does not preserve the Enum type as expected.

Reproduce the code example:

import numpy as np
from enum import Enum, auto



class TestEnum(str, Enum):
    first = auto()
    second = auto()


cond = np.array([True, False, False])
a = np.array([TestEnum.first, None, None])
b = TestEnum.second
np.where(cond, a, b) 
# now: array([<TestEnum.first: '1'>, 'T', 'T'], dtype=object)
# expected: array([<TestEnum.first: 1>, <TestEnum.second: 2>, <TestEnum.second: 2>], dtype=object)

When class TestEnum(Enum):, it works well.

Error message:

No response

Runtime information:

1.24.0
3.8.15 | packaged by conda-forge | (default, Nov 22 2022, 08:49:35)
[GCC 10.4.0]

Context for the issue:

xref BUG: enum not properly handled by fillna · Issue #51941 · pandas-dev/pandas

@luke396 luke396 changed the title BUG: np.where may not preserve Enum type when used with a mix of Enum and non-Enum values BUG: np.where may not preserve Enum type when used with a mix of Enums defined using a custom class that inherits from both str and Enum Mar 18, 2023
@maniben3
Copy link

import numpy as np
from enum import Enum, auto

class TestEnum(str, Enum):
first = auto()
second = auto()

cond = np.array([True, False, False])
a = np.array([TestEnum.first, None, None])
b = (TestEnum.second)
b=np.array(b,dtype=np.object)
np.where(cond, a, b)

:14: DeprecationWarning: np.object is a deprecated alias for the builtin object. To silence this warning, use object by itself. Doing this will not modify any behavior and is safe.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
b=np.array(b,dtype=np.object)
array([<TestEnum.first: '1'>, <TestEnum.second: '2'>,
<TestEnum.second: '2'>], dtype=object)

#use with np.object

@luke396
Copy link
Author

luke396 commented Mar 18, 2023

b = np.array(TestEnum.second) indeed works.

@luke396 luke396 closed this as completed Mar 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants