0

I'm trying to create an array of of the number of elements I have in another array, but appending to the array in a loop gives me too many numbers.

 xaxis = np.zeros(len(newdates))
 for i in newdates:
    xaxis = np.append(xaxis, i)

Instead of [1,2,3,4,.....] like I want, it's giving me an array of [1,1,2,1,2,3,1,2,3,4,.....].

This seems like an easy question, but it's hanging me up for some reason.

4 Answers 4

1

You can avoid the loop entirely with something like (assuming len(newdates) is 3):

>>> np.array(range(1, len(newdates)+1))
array([1, 2, 3])
Sign up to request clarification or add additional context in comments.

2 Comments

np.arange is probably faster
Ah, good call. That would make the answer: np.arange(1, len(newdates)+1)
1

You are appending i values, the values inside newdates, to xaxis list, which is [0]*len(newdates). The code below illustrates this:

>>> import numpy as np
>>> newdates = range(10)
>>> xaxis = np.zeros(len(newdates))
>>> for i in newdates:
...     xaxis = np.append(xaxis, i)
... 
>>> print xaxis
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  2.  3.  4.  5.  6.  7.
  8.  9.]

I'm not sure about what you want to do, but I think it could be easily solved by:

xaxis = range(len(newdates))

Comments

0

Instead of

xaxis = np.append(xaxis, i)

try using the extend function

np.extend(i)

1 Comment

Doing that just keeps the array filled with zeros.
0

While someone gave you a better way to do it I feel you should also see what you're doing wrong

for foo in bar:

loops over all of the elements of bar and calls them foo within the for loop. So if I had

newdates = [10,9,8,7,6,5,4,3,2,1]

and I did your code

xaxis = np.zeros(len(newdates))
 for i in newdates:
    xaxis = np.append(xaxis, i)

xaxis would be a bunch of 0's the length of newdates and then the numbers in newdates because within the loop i corresponds to an element of newdates

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.