簡體   English   中英

將 numpy 數組重塑為類似於具有任意嵌套子數組的不同數組

[英]Reshaping numpy array to be similar to different array with arbitrarily nested subarrays

我有兩個 arrays ab 如果我運行a.shape我得到(10,)並且如果我運行(b.shape)我得到(10,)但是這些值中的每一個都是任意嵌套的 arrays ,它們在形狀上不等於其他本身或另一個數組中的對應值。 例如a[0].shape返回(122,)b[0].shape返回(3900,)b[5].shape返回(5200,64)因此它們在同一個數組中甚至不一致。

我知道它們使用在迭代 Python中找到的遞歸解決方案具有相同的元素總數(沒有標准的 numpy 函數似乎能夠盡可能深入地鑽入數組):

def iterThrough(lists):
  if not hasattr(lists[0], '__iter__'):
    for val in lists:
      yield val
  else:
    for l in lists:
      for val in iterThrough(l):
        yield val
            si = 0

for value in iterThrough(a): #and b
    si += 1

兩者都返回3066752 我知道這很混亂,但是我需要它處於那種形狀才能稍后計算數學 function,我猜這樣做比重寫該方程以反映格式良好的數組更容易。

如何使數組a在其所有嵌套形狀中與數組b完全相同?

這是一個可以完成這項工作的解決方案,但保證速度很慢,因為它是遞歸的、迭代的,並且根本不向量化:

import copy

# Generator function:
# Returns successive scalars from any crazily nested array
def arr_values(arr):
    for elem in arr:
        if (isinstance(elem, np.ndarray)):
            for sub_arr_elem in arr_values(elem):
                yield sub_arr_elem
        else:
            yield elem

# Generator function:
# Returns successive tuples (vector, index) from any arbitrarily nested array,
# such that assigning a value to vector[index] is the same as assigning the value
# to a position in the input array.
def arr_positions(arr):
    for pos,elem in enumerate(arr):
        if (isinstance(elem, np.ndarray)):
            for inner_arr_pos in arr_positions(elem):
                yield inner_arr_pos
        else:
            yield arr, pos

# Create a new array, having the shape of `b` (and incidentally, b's data also)
arr_in_shape_of_b = copy.deepcopy (b)

# Get the iterator for successive assignable positions in
# our destination array
iter_dest = arr_positions(arr_in_shape_of_b)

# Get the iterator for successive scalars from our source array
iter_src = arr_values(a)

# Now, iterate over the two iterators in tandem, and
# perform assignment of successive values from source,
# into successive positions in destination.
for ((dest_vec, pos), val) in zip(iter_dest, iter_src):
    dest_vec[pos] = val

測試一下:

我用這個演示數據測試了ab

a = np.array ([np.arange(6).reshape(2,3), np.array([np.arange(8).astype(np.ndarray),
                                                    23], dtype=np.ndarray),24], dtype=np.ndarray)
print (a.shape)
print (a)

b = np.roll(-1 * a, 2, axis=0)
print (b.shape)
print (b)

因此,輸入 arrays ab如下所示:

(3,)
[array([[0, 1, 2],
       [3, 4, 5]])
 array([array([0, 1, 2, 3, 4, 5, 6, 7], dtype=object), 23], dtype=object)
 24]
(3,)
[array([array([0, -1, -2, -3, -4, -5, -6, -7], dtype=object), -23],
      dtype=object)
 -24 array([[ 0, -1, -2],
       [-3, -4, -5]])]

output 看起來像這樣:

(3,)
[array([array([0, 1, 2, 3, 4, 5, 0, 1], dtype=object), 2], dtype=object) 3
 array([[ 4,  5,  6],
       [ 7, 23, 24]])]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM