0

I need to print each row in a data frame. I used iterrow() to print, but the rows printed were tuples. I want to retain each row a dataframe

please refer to the below code

def rowprint(df):
    if len(df):
       for row in iterrows():
           print(row['col1'])

if __name__ == '__main__':
       df= df.loc[df['col3']=='value']
       rowprint(df)

error: tuple indices must be integers or slices, not str

3 Answers 3

1

iterrows returns both the index and the row's Series.

You can expand to two parameters:

def rowprint(df):
    if len(df):
       for index, row in iterrows():
           print(row['col1'])

Alternatively, as you subset a single column anyway, iterate on the column:

def rowprint(df):
    if len(df) and 'col1' in df:
       for value in df['col1']:
           print(value)
Sign up to request clarification or add additional context in comments.

Comments

1

You forgot the index:

def rowprint(df):
    if len(df):
       for index, row in df.iterrows():
           print(row['col1'])

Comments

1

Since as you noticed iterrows() returns a tuple, what you can do is

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

That way you assign each element of the tuple to the 2 variables and you can just not use the "index" variable.

Python supports assigning a value to multiple variables at a time for example when you have a tuple.

a, b = (1, 2)
a, b, c, d = (1, 2, "Max", "")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.