我有3D numpy陣列,我只想要獨特的2D子陣列。Numpy獨特的2D子陣列
輸入:
[[[ 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
我也試過的看法,但我真的不知道如何使用它。 你能幫我嗎?
這是一個[新功能](https://github.com/numpy/numpy/pull/7742)在即將到來的1.13中,作爲'np.unique(a,axis = 0)'。你可以簡單地複製新的實現並在你的代碼中使用它,因爲1.13還沒有發佈 – Eric