我遇到了同样的问题,并最终进行了反向处理,在正常连接(带副本)后,我将原始数组重新分配为连接数组上的视图:
import numpy as np
def concat_no_copy(arrays):
""" Concats the arrays and returns the concatenated array
in addition to the original arrays as views of the concatenated one.
Parameters:
-----------
arrays: list
the list of arrays to concatenate
"""
con = np.concatenate(arrays)
viewarrays = []
for i, arr in enumerate(arrays):
arrnew = con[sum(len(a) for a in arrays[:i]):
sum(len(a) for a in arrays[:i + 1])]
viewarrays.append(arrnew)
assert all(arr == arrnew)
return con, viewarrays
您可以如下进行测试:
def test_concat_no_copy():
arr1 = np.array([0, 1, 2, 3, 4])
arr2 = np.array([5, 6, 7, 8, 9])
arr3 = np.array([10, 11, 12, 13, 14])
arraylist = [arr1, arr2, arr3]
con, newarraylist = concat_no_copy(arraylist)
assert all(con == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14]))
for old, new in zip(arraylist, newarraylist):
assert all(old == new)