Chris
Chris

Reputation: 1680

Iterate over a numpy array of dates

I'm trying to iterate over a range of dates I've pulled from a Pandas dataframe; sample below.

enter image description here

Code below initially threw the following error

TypeError: 'numpy.datetime64' object is not iterable

r1 = pd.read_sql("select * from myTable",conn)    
...

dates = np.sort(r1['date'].unique())       

for i, d in dates:

   z_d = z[z['date']==d]
   r1_d = r1[r1['date']==d]
...

after googling, I tried applying the iditer numpy method, but doing so gives the following error:

TypeError: iteration over a 0-d array

 r1 = pd.read_sql("select * from myTable",conn)    
 ...

 dates = np.sort(r1['date'].unique())       

 for i, d in np.nditer(dates):

    z_d = z[z['date']==d]
    r1_d = r1[r1['date']==d]
 ...

How to amend this to loop over the list of dates included in the dates variable?

Upvotes: 0

Views: 968

Answers (2)

Mark Reed
Mark Reed

Reputation: 95252

for d in dates will assign d to each date in turn; for i,d in dates doesn't work because you can't assign a single date value to two variables (it is basically trying to do i,d = dates[0] etc.) If you also want the index, Python doesn't give you that for free with its for loop; you have to use the enumerate function to prepend the index to each item, and then loop over the result of that: for i,d in enumerate(dates):. Fortunately, enumerate returns a lazy iterator, so it's efficient; it doesn't generate all the indices first. But you get the same output as if it had, and you can see that result with list(enumerate(dates)), which will return something like [(0,'first-date'), (1, 'second-date'), ...]. So the assignments become i, d = (0, 'first-date') and so on, which work fine.

Upvotes: 1

A Kruger
A Kruger

Reputation: 2419

Your for loop has two variables, so it's expecting two inputs from the array elements. The errors are because it's trying to parse or iterate over the strings. Change it to

for d in dates:

Upvotes: 0

Related Questions