John M
John M

Reputation: 273

Replacing a column with another predefined column

Currently I have a very simple question. I'm using Python 2.7 and have the following.

from pylab import *
import numpy as np

Nbod = 55800
Nsteps = 7
r = zeros(shape=(Nbod, Nsteps))
r_i = np.random.uniform(60.4,275,Nbod)

r[1:Nbod][0] = r_i 

I'm trying to replace the first column r[1:end][0] with r_i. I'm getting the following error from my ipython notebook compiler.

ValueError                                Traceback (most recent call last)
/home/john/<ipython-input-6-1b7fabbd1fa9> in <module>()
----> 1 r[:][0] = r_i #impose the initial conditions of radial and
      2               #theta coordinates at the first time step


ValueError: operands could not be broadcast together with shapes (7) (55800)

I tried to transpose the r[0] vector but still got the same issue. I'm not quite sure I've followed correct format for questions on this forum so leave a comment and I will edit accordingly.

Upvotes: 0

Views: 45

Answers (1)

Daniel
Daniel

Reputation: 19547

I think you want this:

>>> import numpy as np
>>> Nbod = 55800
>>> Nsteps = 7
>>> r = np.zeros(shape=(Nbod, Nsteps))
>>> r_i = np.random.uniform(60.4,275,Nbod)^C

#Notice that we slice the 2nd column and replace it with r_i
>>> r[:,1] = r_i

#Examine the first row
>>> r[0]
array([   0.       ,  105.6566683,    0.       ,    0.       ,
          0.       ,    0.       ,    0.       ])

Slicing a numpy array like a list of list is not appropriate here, make sure you use the numpy slicing operations for efficiency and extra capabilities. More information on slicing can be found here.

Upvotes: 1

Related Questions