Home > Net >  Print each rows in a Dataframe
Print each rows in a Dataframe

Time:04-01

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

CodePudding user response:

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)

CodePudding user response:

You forgot the index:

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

CodePudding user response:

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", "")
  • Related