I have a numpy array of different numpy arrays and I want to make a deep copy of the arrays. I found out the following:
import numpy as np pairs = [(2, 3), (3, 4), (4, 5)] array_of_arrays = np.array([np.arange(a*b).reshape(a,b) for (a, b) in pairs]) a = array_of_arrays[:] # Does not work b = array_of_arrays[:][:] # Does not work c = np.array(array_of_arrays, copy=True) # Does not work d = np.array([np.array(x, copy=True) for x in array_of_arrays]) array_of_arrays[0][0,0] = 100 print a[0][0,0], b[0][0,0], c[0][0,0], d[0][0,0]
Is d the best way to do this? Is there a deep copy function I missed? And what is the best way to interact with each element in this array of different sized arrays?
deepcopy() function takes the array as an input argument and returns a deep copy of the array. The following code example shows us how to deep copy a NumPy array with the copy. deepcopy() function in Python. In the above code, we deep copied the NumPy array array inside the array2 with the copy.
Use numpy. copy() function to copy Python NumPy array (ndarray) to another array. This method takes the array you wanted to copy as an argument and returns an array copy of the given object. The copy owns the data and any changes made to the copy will not affect the original array.
copy() function creates a deep copy. It is a complete copy of the array and its data, and doesn't share with the original array.
import numpy as np import copy pairs = [(2, 3), (3, 4), (4, 5)] array_of_arrays = np.array([np.arange(a*b).reshape(a,b) for (a, b) in pairs]) a = copy.deepcopy(array_of_arrays)
Feel free to read up more about this here.
Oh, here is simplest test case:
a[0][0,0] print a[0][0,0], array_of_arrays[0][0,0]
Beaten by one minute. Indeed, deepcopy is the answer here.
To your second question abut indexing: I have a feeling that you may be better off with a simple list or a dictionary-type data structure here. np.arrays make sense primarily if each array element is of the same type. Of course you can argue that each element in array_of_arrays is another array, but what is the benefit of having them collected in a numpy array instead of a simple list?
list_of_arrays = [np.arange(a*b).reshape(a,b) for (a, b) in pairs]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With