Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copy of a np.array of np.array

Tags:

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?

like image 992
Dominik Müller Avatar asked Jun 02 '16 13:06

Dominik Müller


People also ask

Does NP array make a deep copy?

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.

How do I create a copy of a NumPy array?

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.

Which function of NumPy should be used to make deep copy of an 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.


2 Answers

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] 
like image 189
Tomasz Plaskota Avatar answered Nov 05 '22 06:11

Tomasz Plaskota


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] 
like image 45
maschu Avatar answered Nov 05 '22 07:11

maschu