如何通过for循环构建和填充pandas数据框? [英] How to build and fill pandas dataframe from for loop?

查看:260
本文介绍了如何通过for循环构建和填充pandas数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在运行的代码的一个简单示例,我希望将结果放入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

使用此代码:

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

pd.DataFrame(d)

我可以得到:

    Passer Rating   Player      Team
  0 55.8            A.Rodgers   GB

这是一个1x3数据帧,我理解为什么它只是一行,但是我不知道如何使列以正确的顺序变为多行.理想情况下,该解决方案将能够处理 n 个行数(基于p),并且如果通过请求的统计信息数来设置列数,那将是很棒的(尽管不是必须的).有什么建议?预先感谢!

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!

推荐答案

尝试使用列表理解:

import pandas as pd

df = pd.DataFrame(
    [p, p.team, p.passing_att, p.passer_rating()] for p in game.players.passing()
)

这篇关于如何通过for循环构建和填充pandas数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆