4

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?

5 Answers 5

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

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
If that which should be entered is in an iterable I you could simply do data1[:, 3] = I
3
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.

Comments

2

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!

Comments

0

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

Comments

-1

hey guys if u want to fill an array with just the same number just

x_2 = np.ones((1000))+1

exemple for 1000 numbers 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.