全部,
我在数据框中有一列,如下所示:
allHoldingsFund['BrokerMixed']
Out[419]:
78 ML
81 CITI
92 ML
173 CITI
235 ML
262 ML
264 ML
25617 GS
25621 CITI
25644 CITI
25723 GS
25778 CITI
25786 CITI
25793 GS
25797 CITI
Name: BrokerMixed, Length: 2554, dtype: object
虽然列是一个对象。我无法按该列分组,甚至无法提取该列的唯一值。例如,当我这样做时:
allHoldingsFund['BrokerMixed'].unique()
我收到一个错误
uniques = table.unique(values)
File "pandas/_libs/hashtable_class_helper.pxi", line 1340, in pandas._libs.hashtable.PyObjectHashTable.unique
TypeError: unhashable type: 'numpy.ndarray'
当我分组时,我也收到错误消息。
欢迎任何帮助。谢谢
最佳答案
看起来您的系列中有一个 NumPy 数组。但是你不能散列 NumPy 数组和 pd.Series.unique
, 喜欢 set
, 依赖于散列。
如果您不能确保您的系列数据只包含字符串,您可以在调用 pd.Series.unique
之前将 NumPy 数组转换为元组。 :
s = pd.Series([np.array([1, 2, 3]), 1, 'hello', 'test', 1, 'test'])
def tuplizer(x):
return tuple(x) if isinstance(x, (np.ndarray, list)) else x
res = s.apply(tuplizer).unique()
print(res)
array([(1, 2, 3), 1, 'hello', 'test'], dtype=object)
当然,这意味着您的数据类型信息会在结果中丢失,但至少您可以看到“唯一”的 NumPy 数组,前提是它们是一维的。
关于python - df ['X' ].unique() 和 TypeError : unhashable type: 'numpy.ndarray' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51675151/