close

How to build and fill pandas dataframe from for loop?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to build and fill pandas dataframe from for loop in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to build and fill pandas dataframe from for loop?

  1. How to build and fill pandas dataframe from for loop?

    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() )

  2. build and fill pandas dataframe from for loop

    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() )

Method 1

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])

Method 2

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()
)

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read