Christina Hughes
Christina Hughes

Reputation: 357

How to iterate over Pandas dataframe row & create a dataframe in each iteration

I have a pandas data frame gmat. The sample data looks like

YEAR  student score mail_id      phone            Loc
2012  abc     630   [email protected]  1-800-000-000   pqr
2012  pqr     630   [email protected]  1-800-000-000   abc

I would like to iterate through this data frame & create a dataframe from rows of this data frame in for loop & use that data frame for doing calculation.Each iteration in for loop will overwrite previous dataframe with the current row in iteration. For example my first data frame in for loop will look like

YEAR  student score mail_id      phone            Loc
2012  abc     630   [email protected]  1-800-000-000   pqr

and second dataframe after overwriting first row will look like

YEAR  student score mail_id      phone            Loc
2012  pqr     630   [email protected]  1-800-000-000   abc

So I tried following code

for row in gmat.iterrows():
    
    df=pd.DataFrame(list(row))

But while checking I'm seeing df is not populated properly. It's only showing 2 columns Can you please suggest me how to do it?

I also tried this based on Georgy's suggestion, I used for index, row in gmat.iterrows(). Here I'm getting row as a pd.Series then I'm using gmrow=pd.DataFrame(row) But my column heading of original data is coming as row. Data I'm getting as YEAR 2012 student abc score 630 mail_id [email protected] phone 1-800-000-000 Loc pqr

Upvotes: 2

Views: 7280

Answers (1)

Shrinivas Deshmukh
Shrinivas Deshmukh

Reputation: 697

You can slice your dataframe like this:

for index, row in gmat.iterrows(): x = df[index:index+1] print("print iterations:",x)

print is just an example. You can do your desired transformations with x

Upvotes: 5

Related Questions