1

I must read each row of an excel file and preform calculations based on the contents of each row. Each row is divided in columns, my problem is that I cannot find a way to access the contents of those columns.

I'm reading the rows with:

for i in df.index,:
    print(df.loc[i])

Which works well, but when I try to access, say, the 4h column with this type of indexing I get an error:

for i in df.index,:
    print(df.loc[i][3])

I'm pretty sure I'm approaching the indexing issue in the wrong way, but I cannot figure put how to solve it.

  • there is `iterrows()` for a dataframe. Look [here](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html) – Rolando cq Feb 11 '19 at 18:15
  • 2
    You normally do not iterate through the rows of a dataframe. You may expect a more useful answer if you provide an example of your dataframe and the operation that you want to apply. – DYZ Feb 11 '19 at 18:17
  • also, loc does not give you a list to access, would be `.loc[column]` `.loc[column, index]`, `.loc[[columns,...],[indexs,...]]` [Here](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html) – Rolando cq Feb 11 '19 at 18:18
  • `loc` is used to access data by labels (column names or indices), `iloc` is used to access data by row and column position (i.e. integer). You can combine them: `df.loc[some_index].iloc[3]` – Tarifazo Feb 11 '19 at 18:23

1 Answers1

5

You can use iterrows(), like in the following code:

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

But this is not the most efficient way to iterate over a panda DataFrame, more info at this post.

Gustavo Morais
  • 548
  • 6
  • 17
Lucas Araújo
  • 429
  • 5
  • 17