Ank
Ank

Reputation: 1904

numpy array assign values from another array

If I do something like this:

import numpy as np
b=np.array([1,2,3,4,5])
c=np.array([0.6,0.7,0.8,0.9])
b[1:]=c

I get b =

array([1,0,0,0,0])

It works fine if c only contains integers. But I have fractions. I wish to get something like this:

array([1,0.6,0.7,0.8,0.9])

How can I achieve that?

Upvotes: 3

Views: 8493

Answers (4)

Paul Panzer
Paul Panzer

Reputation: 53029

If you don't know whether the types are matched or not it is more economical to either use .astype with the copy flag set to False or to use np.asanyarray:

>>> b_float = np.arange(5.0)
>>> b_int = np.arange(5)
>>> c = np.arange(0.6, 1.0, 0.1)
>>> 

>>> b = b_float.astype(float)
# astype makes an unnecessary copy
>>> np.shares_memory(b, b_float)
False

# avoid this using the copy flag ...
>>> b = b_float.astype(float, copy=False)
>>> b is b_float
True

# or asanyarray
>>> b = np.asanyarray(b_float, dtype=float)
>>> b is b_float
True

# if the types do not match the flag has no effect
>>> b = b_int.astype(float, copy=False)
>>> np.shares_memory(b, b_int)
False

# likewise asanyarray does make a copy if it must
>>> b = np.asanyarray(b_int, dtype=float)
>>> np.shares_memory(b, b_int)
False

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

The problem is because of the typecasting. It's basically better to have both arrays in the same type before reassigning the items. If it's not possible you can use another function to create your desire array. In this case you can use np.concatenate():

In [16]: np.concatenate((b[:1], c))
Out[16]: array([ 1. ,  0.6,  0.7,  0.8,  0.9])

Upvotes: 1

jpp
jpp

Reputation: 164623

Numpy arrays are strongly typed. Make sure your arrays have the same type, like this:

import numpy as np

b = np.array([1, 2, 3, 4, 5])
c = np.array([0.6, 0.7, 0.8, 0.9])

b = b.astype(float)
b[1:] = c

# array([ 1. ,  0.6,  0.7,  0.8,  0.9])

You can, if you wish, even pass types from other arrays, e.g.

b = b.astype(c.dtype)

Upvotes: 4

Pratik Kumar
Pratik Kumar

Reputation: 2231

instead of b=np.array([1,2,3,4,5]) which stores elemnts an integers do b=np.array([1,2,3,4,5]).astype(float) which will store elements as float then perform b[1:]=c

Upvotes: 1

Related Questions