Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy data from a numpy array to another

Tags:

python

numpy

What is the fastest way to copy data from array b to array a, without modifying the address of array a. I need this because an external library (PyFFTW) uses a pointer to my array that cannot change.

For example:

a = numpy.empty(n, dtype=complex) for i in xrange(a.size):   a[i] = b[i] 

It is possible to do it without a loop?

like image 308
Charles Brunet Avatar asked Jun 21 '11 21:06

Charles Brunet


People also ask

How do I copy a NumPy 2D array in Python?

Create a Copy of 2D Arrays Using the NumPy copy() Function NumPy offers the copy() function. The copy() function can be implemented as shown below. In the example code, we created a copy of the original array and changed the copy. However, we have retained the original copy of the array, printed in the last line.

How do I copy an NP array in Python?

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.


2 Answers

I believe

a = numpy.empty_like(b) a[:] = b 

will copy the values quickly. As Funsi mentions, recent versions of numpy also have the copyto function.

like image 142
Brian Hawkins Avatar answered Sep 21 '22 06:09

Brian Hawkins


NumPy version 1.7 has the numpy.copyto function that does what you are looking for:

numpy.copyto(dst, src)

Copies values from one array to another, broadcasting as necessary.

See: https://docs.scipy.org/doc/numpy/reference/generated/numpy.copyto.html

like image 24
Funsi Avatar answered Sep 23 '22 06:09

Funsi