繁体   English   中英

返回 dtype=object 的 np.array 中非 NaN 唯一值的索引

[英]Return indices of non-NaN uniques in np.array of dtype=object

如何返回与 dtype dtype=objectnp.array中的唯一值对应的索引列表?

类似于:

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]

请注意arrdtype=object因为它包含可变数据类型intstr

先感谢您!

在第一个示例中,数组是字符串 dtype:

In [293]: arr = np.array(["one", "one", 2, 2])
In [294]: arr
Out[294]: array(['one', 'one', '2', '2'], dtype='<U21')
In [295]: np.unique(arr)
Out[295]: array(['2', 'one'], dtype='<U21')

如果我们指定 object dtype

In [298]: arr = np.array(["one", "one", 2, 2], object)
In [299]: arr
Out[299]: array(['one', 'one', 2, 2], dtype=object)
In [300]: np.unique(arr)
Traceback (most recent call last):
  ...
  File "/usr/local/lib/python3.8/dist-packages/numpy/lib/arraysetops.py", line 333, in _unique1d
    ar.sort()
TypeError: '<' not supported between instances of 'int' and 'str'

请注意回溯中的排序

你的nan是什么?

In [306]: arr = np.array([nan, "one", 2, 2])
Traceback (most recent call last):
  File "<ipython-input-306-abe4f4fe7b97>", line 1, in <module>
    arr = np.array([nan, "one", 2, 2])
NameError: name 'nan' is not defined

In [307]: arr = np.array([np.nan, "one", 2, 2])
In [308]: arr
Out[308]: array(['nan', 'one', '2', '2'], dtype='<U32')

nan是一个浮点数:

In [309]: arr = np.array([np.nan, 3, 2, 2])
In [310]: arr
Out[310]: array([nan,  3.,  2.,  2.])
In [311]: np.unique(arr)
Out[311]: array([ 2.,  3., nan])

浮点数上unique性可能会很棘手,因为如果浮点数并不总是“相等”

np.unique使用np.lib.arraysetops._unique1dnan有一些特殊处理(因为nan不等于任何东西,甚至不等于它本身)。

示例字符串排序

In [321]: np.sort(['one','a','B','','_',' '])
Out[321]: array(['', ' ', 'B', '_', 'a', 'one'], dtype='<U3')

自从我查看字符串排序(ASCII 字符)以来已经有一段时间了,所以不能确切地说出顺序是什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM