Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 551
Ank Avatar asked May 11 '26 22:05

Ank


2 Answers

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)
like image 77
jpp Avatar answered May 13 '26 11:05

jpp


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
like image 23
Paul Panzer Avatar answered May 13 '26 11:05

Paul Panzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!