MathiasRa
MathiasRa

Reputation: 835

Python: How to make nested loop work?

I am trying get each data point from a data point with 13 columns and 13xx rows. And I figured I could make a nested loop to get each data point, however the code below is not working:

i = 0
for row in data.itertuples():
    while i < len(da) - 1:
        price = row[i:i+1]
        price, = price
        print(price)
        i += 1

These are the only values I get (which is from one row only). How do I get all of the rows?

2011-12-12 00:00:00 64.58 64.92 63.935 64.31 8793500.0 0.0 1.0 53.7727555366 54.0558576872 53.235694104

Upvotes: 0

Views: 67

Answers (3)

Cole DeLavergne
Cole DeLavergne

Reputation: 13

I am not a Python expert but if I were writing this in C# I would nest for's instead of using the while. In my experience you should use while only when it's appropriate and in this case we have a much easier way of looping this code. You've already determined the rows with your first loops so the next steps to display columns would be to search those rows for the columns. If you want to stick with the "i=0" then foreach column is the way to go. However, foreach is more taxing on your program than just using for and while isn't needed(for is twice as fast as foreach). You want to avoid the possibility of going into the infinite loop hell. Again not a python expert but using just a for statement to find the columns, as Daniel above suggested, seems like it would work great here.

Upvotes: 0

Stuart Buckingham
Stuart Buckingham

Reputation: 1774

Move the counter into the for block:

for row in data.itertuples():
    i = 0
    while i < len(da) - 1:
        price = row[i:i+1]
        price, = price
        print(price)
        i += 1

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599450

Why not an actual nested loop?

for row in data:
    for column in row:
        print(column)

Upvotes: 0

Related Questions