Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare and fill an array in NumPy?

I need to create an empty array in Python and fill it in a loop method.

data1 = np.array([ra,dec,[]])

Here is what I have. The ra and dec portions are from another array I've imported. What I am having trouble with is filling the other columns. Example. Lets say to fill the 3rd column I do this:

for i in range (0,56):
    data1[i,3] = 32

The error I am getting is:

IndexError: invalid index for the second line in the aforementioned code sample.

Additionally, when I check the shape of the array I created, it will come out at (3,). The data that I have already entered into this is intended to be two columns with 56 rows of data.

So where am I messing up here? Should I transpose the array?

like image 599
handroski Avatar asked Jan 11 '23 03:01

handroski


2 Answers

You could do:

data1 = np.zeros((56,4))

to get a 56 by 4 array. If you don't like to start the array with 0, you could use np.ones or np.empty or np.ones((56, 4)) * np.nan

Then, in most cases it is best not to python-loop if not needed for performance reasons. So as an example this would do your loop:

data[:, 3] = 32
like image 161
deinonychusaur Avatar answered Jan 21 '23 07:01

deinonychusaur


data1 = np.array([ra,dec,[32]*len(ra)])

Gives a single-line solution to your problem; but for efficiency, allocating an empty array first and then copying in the relevant parts would be preferable, so you avoid the construction of the dummy list.

like image 28
Eelco Hoogendoorn Avatar answered Jan 21 '23 07:01

Eelco Hoogendoorn