mike reed
mike reed

Reputation: 3

unable to iterate over rows in Pandas Dataframe

I know this question has been asked many times but I have tried almost all methods I am trying to iterate over rows in DataFrame using following code.

import pandas as pd

df = pd.read_csv(r"file.csv")

for row in df:
    print(row)

there is only one column in csv file and it only prints header of file. I have also used .items() , .iterrows() and .itertuples(), all these methods give tuples as output which I don't need. Further task I am trying to do in loop only accepts output from for row in df:. kindly help that how can I print actual rows this way rather than just header name. Thank you.

Upvotes: 0

Views: 4399

Answers (2)

Ajay A
Ajay A

Reputation: 1068

Try this, using the specific column on which you want to iterate

for row in df[col_name].to_list():

Upvotes: 1

Linden
Linden

Reputation: 571

The df.iterrows() method iterates over each row of a dataframe, returning a tuple of (row_number, row_data). So to just get the row data, you can unpack each tuple as part of the iterration and only use the second part:

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

Upvotes: 2

Related Questions