How to iterate over row in a Dataframe in Pandas?

0 votes

I have a dataframe from pandas:

import pandas as pd
inp = [{'c1':1, 'c2':10}, {'c1':11,'c2':13}, {'c1':12,'c2':14}]
df = pd.DataFrame(inp)
print df
And the output is:
   c1   c2
0  1    10
1  11   13
2  12   14
Now I want to iterate over the rows of this frame. For every row I want to be able to access its elements (values in cells) by the name of the columns.
Jul 18 in Python by Shabnam
• 920 points
138 views

1 answer to this question.

0 votes

Hi,

You can use df.iterrows(), it yields both index and row.

Input:

import pandas as pd
import numpy as np
df = pd.DataFrame([{'c1':1, 'c2':10}, {'c1':11,'c2':13}, {'c1':12,'c2':14}])

for index, row in df.iterrows():
    print(row['c1'], row['c2'])

Output:

  1  10
  11 13
  12 14
answered Jul 18 by Taj
• 1,040 points

Related Questions In Python

0 votes
1 answer

How to convert a Pandas GroupBy object to DataFrame in Python

g1 here is a DataFrame. It has a hierarchical index, ...READ MORE

answered Nov 12, 2018 in Python by Nymeria
• 3,520 points
9,445 views
0 votes
1 answer

How to find if a value exists in Pandas dataframe?

Try this:​ for name in df['Name']: ...READ MORE

answered Apr 8 in Python by Tina
3,500 views
0 votes
1 answer

How to append a row to a Pandas dataframe?

You can use the append method provided by pandas ...READ MORE

answered May 9 in Python by Raj
391 views
0 votes
1 answer

How to iterate over a string when there is successive increase in its length?

The following code might help -  mystring = ...READ MORE

answered Jul 22 in Python by Arvind
• 2,960 points
24 views
0 votes
1 answer

How to rename columns in pandas (Python)?

It is easy by just adding ".columns" ...READ MORE

answered Apr 30, 2018 in Data Analytics by DeepCoder786
• 1,720 points
158 views
0 votes
1 answer

What is the Difference in Size and Count in pandas (python)?

The major difference is size includes NaN ...READ MORE

answered Apr 30, 2018 in Data Analytics by DeepCoder786
• 1,720 points
781 views
0 votes
2 answers
0 votes
1 answer

Converting a pandas data-frame to a dictionary

Emp_dict=Employee.to_dict('records') You can directly use the 'to_dict()' function ...READ MORE

answered May 23, 2018 in Data Analytics by Bharani
• 4,560 points
1,837 views
0 votes
1 answer

How to create a train and test sample from one dataframe using pandas?

Hi, The below written code can help you ...READ MORE

answered Jul 3 in Python by Taj
• 1,040 points
490 views
0 votes
1 answer

How to convert multiple columns to string in pandas dataframe?

Hi, To convert multiple columns to string, include a list of ...READ MORE

answered Jul 18 in Python by Taj
• 1,040 points
858 views