Domanda

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.

È stato utile?

Soluzione

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])

Altri suggerimenti

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))

Instead of

xaxis = np.append(xaxis, i)

try using the extend function

np.extend(i)

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top