0

i have a dataframe that looks like this:

Open        High  ...  Dividends  Stock Splits
Date                                ...                         
2021-01-04  118.759295  119.907541  ...      0.194             0
2021-01-05  118.299996  120.137196  ...      0.000             0
2021-01-06  118.509677  123.691787  ...      0.000             0
2021-01-07  124.141101  127.286317  ...      0.000             0
2021-01-08  126.297817  127.446072  ...      0.000             0
2021-01-11  126.257878  129.143486  ...      0.000             0
2021-01-12  128.135026  128.194933  ...      0.000             0
2021-01-13  127.266345  127.855453  ...      0.000             0

when i do

for index, row in df.iterrows():
 print(index)

i just get the Date column.

but what i want to know is which row (0, 1, 2, 3, 4...) im on. how do i reference that?

new coding
  • 17
  • 6
  • 1
    Sounds like the Date column is your index. Try using `df.reset_index(inplace=True)` first. Then run your loop again – chatax Jun 19 '21 at 18:37
  • you can also use `iloc` (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html) to reference a specific row. `row = df.iloc[2]` and `print(row)` for the third row for example. – David Erickson Jun 19 '21 at 18:39
  • Also, this is a classic answer... https://stackoverflow.com/a/55557758/6366770 ... you shouldn't use iterrows like this if you ever want to progress with pandas. – David Erickson Jun 19 '21 at 18:41

2 Answers2

1

You can get the range index by doing a reset_index(), as follows:

df = df.reset_index()

Result:

The required row number 0, 1, 2, ... are the range index that you can now find at the leftmost of the dataframe:

print(df)

         Date        Open        High  Dividends  Stock Splits
0  2021-01-04  118.759295  119.907541      0.194             0
1  2021-01-05  118.299996  120.137196      0.000             0
2  2021-01-06  118.509677  123.691787      0.000             0
3  2021-01-07  124.141101  127.286317      0.000             0
4  2021-01-08  126.297817  127.446072      0.000             0
5  2021-01-11  126.257878  129.143486      0.000             0
6  2021-01-12  128.135026  128.194933      0.000             0
7  2021-01-13  127.266345  127.855453      0.000             0
SeaBean
  • 22,547
  • 3
  • 13
  • 25
0

If you don't mind losing Date column as index:

df.reset_index(inplace=True)
for index, row in df.iterrows():
    print(index)

If you do want to keep Date as index, you can use enumerate

for index, row in enumerate(df.itertuples()):
    print(index, row.Date)
chatax
  • 990
  • 3
  • 17