【发布时间】:2022-01-19 21:56:31
【问题描述】:
如何返回与 np.array 的 dtype=object 中的唯一值对应的索引列表?
类似于:
arr = np.array(["one", "one", 2, 2])
result = np.unique(arr, return_inverse=True)[1]
print(result)
# [1, 1, 0, 0]
但包含 NaN 值以及在索引期间被忽略的值:
arr = np.array([nan, "one", 2, 2])
result = np.unique(arr, return_inverse=True)[1]
print(result)
# TypeError: '<' not supported between instances of 'float' and 'str'
我已经尝试过以下操作:
arr = np.array([nan, "one", 2, 2])
result = np.unique(arr[~np.isnan(arr)], return_inverse=True)[1]
print(result)
# TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the
我想从上面的例子中得到什么:
arr = np.array([nan, "one", 2, 2])
result = #...
print(result)
# [nan, 1, 0, 0]
请注意arr 属于dtype=object,因为它包含可变数据类型int 和str。
提前谢谢你!
【问题讨论】:
-
unique使用排序,因此无法处理数组的混合对象。 -
@hpaulj 是的,这是有道理的。一种可能的解决方法:如果我用空字符串
""替换 NaN 并将数组dtype转换为str我可以对它们进行排序。但是,我希望始终让 NaN 的索引为 0。空字符串是否确保它们首先被索引?有什么想法吗? -
如果你想使用
dtype=object,你不妨使用普通的list并留在 Python 领域 -
你说得对,更有意义
标签: python list numpy unique nan