How to iterate over rows in a Dataframe in pandas (Python)?

0 votes
How to iterate over rows in a Dataframe in pandas (Python)?
May 2, 2018 in Data Analytics by DataKing99
• 8,130 points
2,899 views

7 answers to this question.

0 votes

Follow this code. hope it helps.

for index,row in df.iterrows():
    print(row['a'],row['b'])

answered May 2, 2018 by DeepCoder786
• 1,720 points
0 votes

You can use:

DataFrame.iterrows()

for index, row in df.iterrows():
    print row["c1"], row["c2"]
answered Dec 10, 2018 by Kishore
0 votes

You can also use :

DataFrame.itertuples()

for row in df.itertuples(index=True, name='Pandas'):
    print getattr(row, "c1"), getattr(row, "c2")

itertuples() is supposed to be faster than iterrows()

answered Dec 10, 2018 by Anurag
0 votes
itertuples is a good option.
answered Dec 10, 2018 by Ayman
0 votes

You can also use df.apply(), something like this:

def valuation_formula(x, y):
    return x * y * 0.5
df['price'] = df.apply(lambda row: valuation_formula(row['x'], row['y']), axis=1)
answered Dec 10, 2018 by Lyndsey
0 votes

You can use the df.iloc function as follows:

for i in range(0, len(df)):
    print df.iloc[i]['c1'], df.iloc[i]['c2']
answered Dec 10, 2018 by Farookh
0 votes

You can use IMHO:

for ind in df.index:
     print df['c1'][ind], df['c2'][ind]
answered Dec 10, 2018 by Ishaan

Related Questions In Data Analytics

0 votes
1 answer

How to sample n random rows per group in a dataframe?

You can assign a random ID to ...READ MORE

answered Jul 2, 2018 in Data Analytics by darklord
• 6,170 points
243 views
0 votes
2 answers
0 votes
1 answer

How to select rows in a range from dataframe?

Hi, There are different functions to select or ...READ MORE

answered Aug 30 in Data Analytics by anonymous
• 27,960 points
15 views
0 votes
1 answer
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,550 points
1,434 views
0 votes
4 answers

Python vs. R for data science

I would say both Python and R ...READ MORE

answered Aug 1 in Data Analytics by briny
111 views
0 votes
1 answer
0 votes
1 answer

How to drop rows of Pandas DataFrame whose value in certain coulmns is NaN

Easy Way: This Way we can easily handle ...READ MORE

answered May 7, 2018 in Data Analytics by DeepCoder786
• 1,720 points
663 views