我有一个3D numpy数组,我只想要独特的2D子数组。
输入:
我试着将子数组转换为字符串(使用tostring()方法),然后使用np.unique,但在转换为numpy数组后,它删除了\x00的最后一个字节,因此我无法使用np.fromstring()将其转换回来。
例如:
我也尝试过使用view,但我真的不知道如何使用它。你能帮帮我吗?
输入:
[[[ 1 2]
[ 3 4]]
[[ 5 6]
[ 7 8]]
[[ 9 10]
[11 12]]
[[ 5 6]
[ 7 8]]]
输出:
[[[ 1 2]
[ 3 4]]
[[ 5 6]
[ 7 8]]
[[ 9 10]
[11 12]]]
我试着将子数组转换为字符串(使用tostring()方法),然后使用np.unique,但在转换为numpy数组后,它删除了\x00的最后一个字节,因此我无法使用np.fromstring()将其转换回来。
例如:
import numpy as np
a = np.array([[[1,2],[3,4]],[[5,6],[7,8]],[[9,10],[11,12]],[[5,6],[7,8]]])
b = [x.tostring() for x in a]
print(b)
c = np.array(b)
print(c)
print(np.array([np.fromstring(x) for x in c]))
输出:
[b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00', b'\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00', b'\t\x00\x00\x00\n\x00\x00\x00\x0b\x00\x00\x00\x0c\x00\x00\x00', b'\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00']
[b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'
b'\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08'
b'\t\x00\x00\x00\n\x00\x00\x00\x0b\x00\x00\x00\x0c'
b'\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08']
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-86-6772b096689f> in <module>()
5 c = np.array(b)
6 print(c)
----> 7 print(np.array([np.fromstring(x) for x in c]))
<ipython-input-86-6772b096689f> in <listcomp>(.0)
5 c = np.array(b)
6 print(c)
----> 7 print(np.array([np.fromstring(x) for x in c]))
ValueError: string size must be a multiple of element size
我也尝试过使用view,但我真的不知道如何使用它。你能帮帮我吗?
np.unique(a, axis=0)
。由于1.13尚未发布,您可以简单地复制新实现并将其用于您的代码中。 - Eric