[英]How to get unique elements from a numpy array containing numpy arrays with different lengths?
我有一個嵌套的 numpy 數組 - 它包含許多其他 numpy 子數組,但子數組的長度不同。 主數組arr_main
看起來像這樣:
>>> print(main_arr)
array([[array([3.5525, ..., 4.0138, 4.0139], dtype=float32)],
[array([3.5525, ..., 4.0138, 4.0139], dtype=float32)],
...
[array([3.5525, ..., 4.0138, 4.0139], dtype=float32)]],
dtype=object)
我想做的是只從大的主數組中提取唯一的子數組,所以我想做類似的事情
np.unique(main_arr)
但這會導致錯誤消息ValueError: operands could not be broadcast together with shapes (4613,) (4615,)
。 我猜,這是由於某些子數組的長度不同。
如何從main_arr
中提取唯一的子數組? 如果您知道一些不依賴於 numpy 的解決方案,我們也將不勝感激! tnx
您可以使用字典按長度重新組合 arrays,然后僅提取唯一的。
for array in main_arr:
n = array.size
if n in d:
d[n].append(array)
else:
d[n] = np.array([array])
new_array = np.empty()
for k in d.keys():
new_array.append(np.unique(d[k]))
然而,提取唯一的 arrays 是一個繁重的算法......
The numpy unique function on works on 1 dimensional arrays but here's some logic you could deploy to get an array of unique arrays:
import numpy as np
# Create example array of sub arrays
a = np.array([
np.array([1, 2, 3]), np.array([4, 5, 6, 7]),
np.array([1, 2, 3]), np.array([4, 5, 6, 7])])
# Build array of unique sub arrays
unique = []
for sub_a in a:
if not any([np.array_equal(i, sub_a) for i in unique]):
unique.append(sub_a)
unique_array = np.array(unique)
您可能想更多地考慮可以比較main_arr
的哪些項目組,以確定它們是否有重復項。 這個問題是不言自明的。 您需要按您在 main_arr 中獲得的main_arr
的長度對其進行分組。 之后,您可以在這些組上調用np.unique
。
main_arr = np.array([np.array([3.5525, 3.7895, 4.0139], dtype=float),
np.array([3.5525, 3.7895, 4.0139], dtype=float),
np.array([3.5525, 4.0138, 4.0139, 4.1], dtype=float),
np.array([3.5525, 4.0138, 4.0139], dtype=float),
np.array([3.5525, 4.0138, 4.0139, 4.1], dtype=float),
np.array([3.5525, 3.7895, 4.0138, 4.0139, -1], dtype=float)], dtype=object)
from itertools import groupby
groups = [list(g) for k,g in groupby(sorted(main_arr, key=len), len)]
# (...) instead of [...] is a better choice in order to avoid double iteration
>>> groups
[[array([3.5525, 3.7895, 4.0139]),
array([3.5525, 3.7895, 4.0139]),
array([3.5525, 4.0138, 4.0139])],
[array([3.5525, 4.0138, 4.0139, 4.1 ]),
array([3.5525, 4.0138, 4.0139, 4.1 ])],
[array([ 3.5525, 3.7895, 4.0138, 4.0139, -1. ])]]
>>> [np.unique(g, axis=0) for g in groups]
[array([[3.5525, 3.7895, 4.0139],
[3.5525, 4.0138, 4.0139]]),
array([[3.5525, 4.0138, 4.0139, 4.1 ]]),
array([[ 3.5525, 3.7895, 4.0138, 4.0139, -1. ]])]
您可以連接所有這些 arrays 但您將擁有另一個數據結構numpy
如果您這樣做,則處理不適用於此。
注意:我稍微更改了初始數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.