Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am new to python syntax not new to programing. 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? Thanks for your help everyone

share|improve this question
up vote 4 down vote accepted

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
share|improve this answer
    
I would need to enter a unique value for each element. Would I be able do enter that value using something like data1[2,3] = 32 – handroski Jul 30 '14 at 16:47
    
If that which should be entered is in an iterable I you could simply do data1[:, 3] = I – deinonychusaur Jul 30 '14 at 16:49
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.

share|improve this answer

One thing that nobody has mentioned is that in Python, indexing starts at 0, not 1.

This means that if you want to look at the third column of the array, you actually should address [:,2], not [:,3].

Good luck!

share|improve this answer

Assuming ra and dec are vectors (1-d):

data1 = np.concatenate([ra[:, None], dec[:, None], np.zeros((len(ra), 1))+32], axis=1)

Or 

data1 = np.empty((len(ra), 3))
data[:, 0] = ra
data[:, 1] = dec
data[:, 2] = 32
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.