+2 votes
by (2.6k points)
edited by

There is a DataFrame from pandas:

import pandas as pd
inp = [{'e2':20, 'e3':200}, {'e2':22,'e3':220}, {'e2':23,'e3':230}]
df = pd.DataFrame(inp)
print df

The output it showed:

   e2   e3
0  20  200
1  22  220
2  23  230

After this I want iterate over the rows of this frame. I want to access the elements by the name of the columns. E.x.

for row in df.rows:
   print row['e2'], row['e3']

Can I do this in Pandas?


2 Answers

0 votes
by (2k points)
edited by

 You can yield both index and row using DataFrame.iterrows . E.g.

for index, row in df.iterrows():
    print(row['e2'], row['e3'])

   20 200
   22 220
   23 230

+2 votes
by (10.9k points)
edited by

To iterate rows in a DataFrame you can use the following ways-

 Using DataFrame.itertuples()

for row in df.itertuples(index=True, name=’Pandas’):

print getattr(row,'e2'), getattr(row,'e3')

Related questions

+3 votes
3 answers
0 votes
1 answer
+2 votes
1 answer
asked May 29, 2019 in R Programming by Ritik (3.5k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !