Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build and fill pandas dataframe from for loop? [duplicate]

Tags:

python

pandas

Here is a simple example of the code I am running, and I would like the results put into a pandas dataframe (unless there is a better option):

for p in game.players.passing():     print p, p.team, p.passing_att, p.passer_rating()  R.Wilson SEA 29 55.7 J.Ryan SEA 1 158.3 A.Rodgers GB 34 55.8 

Using this code:

d = [] for p in game.players.passing():     d = [{'Player': p, 'Team': p.team, 'Passer Rating':         p.passer_rating()}]  pd.DataFrame(d) 

I can get:

    Passer Rating   Player      Team   0 55.8            A.Rodgers   GB 

Which is a 1x3 dataframe, and I understand why it is only one row but I can't figure out how to make it multi-row with the columns in the correct order. Ideally the solution would be able to deal with n number of rows (based on p) and it would be wonderful (although not essential) if the number of columns would be set by the number of stats requested. Any suggestions? Thanks in advance!

like image 782
c.j.mcdonn Avatar asked Jan 20 '15 22:01

c.j.mcdonn


People also ask

How do you create a repeated DataFrame?

To generate a repeated values column with each value in output selected randomly in R data frame, we can use replicate function. The replicate function will repeat the vector values up to the number of times we want and each value will be randomly selected.

How do I populate a DataFrame in pandas?

Fill Data in an Empty Pandas DataFrame by Appending Rows First, create an empty DataFrame with column names and then append rows one by one. The append() method can also append rows. When creating an empty DataFrame with column names and row indices, we can fill data in rows using the loc() method.


2 Answers

The simplest answer is what Paul H said:

d = [] for p in game.players.passing():     d.append(         {             'Player': p,             'Team': p.team,             'Passer Rating':  p.passer_rating()         }     )  pd.DataFrame(d) 

But if you really want to "build and fill a dataframe from a loop", (which, btw, I wouldn't recommend), here's how you'd do it.

d = pd.DataFrame()  for p in game.players.passing():     temp = pd.DataFrame(         {             'Player': p,             'Team': p.team,             'Passer Rating': p.passer_rating()         }     )      d = pd.concat([d, temp]) 
like image 80
Nick Marinakis Avatar answered Sep 20 '22 12:09

Nick Marinakis


Try this using list comprehension:

import pandas as pd  df = pd.DataFrame(     [p, p.team, p.passing_att, p.passer_rating()] for p in game.players.passing() ) 
like image 26
Amit Verma Avatar answered Sep 20 '22 12:09

Amit Verma