我有一個 Pandas DataFrame,其中一個名為 myenum 的列具有 0、1 或 2 的值。我試圖將 1s 和 2s 轉換為字串并使用 Enum 的 .name 屬性來提供幫助。
我認為這是一個關于理解 np.where 與 np.vectorize 的本質的問題,因為它們與 DataFrame 系列相關。我很好奇為什么嘗試使用 np.where 會拋出錯誤,但使用 np.vectorize 會起作用。我想從中學習并更好地理解 DataFrames 中的最佳矢量化實踐。
import enum
import numpy as np
import pandas as pd
df = pd.DataFrame() # one column in this df is 'myenum', its values are either 0, 1, or 2
df['myenum'] = [0, 1, 2, 0, 0, 0, 2, 1, 0]
class MyEnum(enum.Enum):
First = 1
Second = 2
# this throws a TypeError - why?
df['myenum'] = np.where(
df['myenum'] > 0,
MyEnum(df['myenum']).name,
''
)
# whereas this, which seems pretty analagous, works. what am i missing?
def vectorize_enum_value(x):
if x > 0:
return MyEnum(x).name
return ''
vect = np.vectorize(vectorize_enum_value)
df['myenum'] = vect(df['myenum'])
uj5u.com熱心網友回復:
您運算式的完整回溯where是:
Traceback (most recent call last):
File "/usr/lib/python3.8/enum.py", line 641, in __new__
return cls._value2member_map_[value]
TypeError: unhashable type: 'Series'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<ipython-input-27-16f5edc71240>", line 3, in <module>
MyEnum(df['myenum']).name,
File "/usr/lib/python3.8/enum.py", line 339, in __call__
return cls.__new__(cls, value)
File "/usr/lib/python3.8/enum.py", line 648, in __new__
if member._value_ == value:
File "/usr/local/lib/python3.8/dist-packages/pandas/core/generic.py", line 1537, in __nonzero__
raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
它是通過將整個系列提供給MyEnum:
In [30]: MyEnum(df['myenum'])
Traceback (most recent call last):
File "/usr/lib/python3.8/enum.py", line 641, in __new__
return cls._value2member_map_[value]
TypeError: unhashable type: 'Series'
...
問題根本不where在于 。
的where,如果我們為它提供字串的有效串列正常作業:
In [33]: np.where(
...: df['myenum'] > 0,
...: [vectorize_enum_value(x) for x in df['myenum']],
...: ''
...: )
Out[33]:
array(['', 'First', 'Second', '', '', '', 'Second', 'First', ''],
dtype='<U6')
第二個引數,串列理解與vectorize.
where是一個函式;Python 在傳入函式引數之前會對其求值。因此每個引數都必須有效。 where是不是一個迭代器,像apply甚至vectorize。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/383032.html
上一篇:在比較資料集中的值后回傳一條訊息并放入一個新列(使用熊貓)
下一篇:我有一個要過濾的資料框
