NoneType'对象没有属性'append'

时间:2019-07-06 13:34:35

标签: python python-2.7 dataframe append

我试图创建一个数据框,其中的列提供一周内所有NFL游戏的统计数据。 但是在NFL中,两支球队得到了“再见”,这意味着他们将在那周不参加比赛,因此没有比赛数据 当我不使用'if game is None'时,它为'hteam = game.home'提供相同的“'NoneType'对象没有属性'home'”,这意味着由于再见,缺少home的数据,但是,当我使用它时,它仍然会给出相同的错误,但是这次是附加部分。 我真的不明白为什么,因为数据附加部分位于if语句内。 预先感谢

我已经尝试了缩进,但是它并没有真正影响任何东西,并且给了我同样的错误

teams= ['KC','NYJ','ATL','BAL','PIT','ARI','JAX','OAK','PHI','IND','SEA','CAR','NYG','NO','MIA','TB','LAC']
df= pd.DataFrame(columns =["Home","Away","Win","hRushYds","hPassYds",
                           'hPuntAvg','hPenYds',"aRushYds","aPassYds",
                           'aPuntAvg','aPenYds',"hScore","aScore"])

def teamStats(h,data):
    w = 0
    game = nflgame.one(2017,1,h,h)
    if game is not None:
        hteam = game.home
        ateam = game.away
        hpass_yds = game.stats_home.passing_yds
        apass_yds = game.stats_away.passing_yds
        hscore = game.score_home
        ascore = game.score_away
        hrush_yds = game.stats_home.rushing_yds
        arush_yds = game.stats_away.rushing_yds
        hpen_yds = game.stats_home.penalty_yds
        apen_yds = game.stats_away.penalty_yds
        hpunt_avg = game.stats_home.punt_avg
        apunt_avg = game.stats_away.punt_avg
        if hteam == game.winner:
            w = 1
        data = data.append({'Home':hteam,'Away':ateam,'Win': w,
                           'hPassYds':hpass_yds,'aPassYds':apass_yds,'hScore': hscore,
                           'aScore':ascore,'hRushYds':hrush_yds,'aRushYds':arush_yds,
                           'hPenYds':hpen_yds,'aPenYds': apen_yds,'hPuntAvg':hpunt_avg,
                           'aPuntAvg': apunt_avg}, ignore_index=True)
        return data

for h in teams:
    df = teamStats(h,df)
df

2 个答案:

答案 0 :(得分:0)

def srcDelomboked = 'build/src-delomboked' task delombok { description 'Delomboks the entire source code tree' def srcJava = 'src/main/java' inputs.files files( srcJava ) outputs.dir file( srcDelomboked ) doFirst { ClassLoader antClassLoader = org.apache.tools.ant.Project.class.classLoader def collection = files( configurations.compile + configurations.testCompile ) def sumTree = collection + fileTree( dir: 'bin' ) sumTree.forEach { File file -> antClassLoader.addURL(file.toURI().toURL()) } ant.taskdef( name: 'delombok', classname: 'lombok.delombok.ant.Tasks$Delombok', classpath: configurations.compile.asPath + configurations.testCompile.asPath ) ant.delombok( from: srcJava, to: srcDelomboked, classpath: sumTree.asPath ) } } sourceSets { main { java { srcDirs = [ srcDelomboked ] } //blow away the old source sets so that we only use the delomboked source sets } test { java { srcDirs += [ srcDelomboked ] } //but add those new source sets to the tests so that their references are available at test time } } compileJava.dependsOn(delombok) bootJar { mainClassName = 'com.myproj.MyMainClass' // you will need this if its a Spring Boot project } teamstats时,您不会从game返回任何内容。 然后,您将返回值分配给None。 因此,现在df可能是df(如果None不存在)。 在game的下一个循环迭代中,您尝试再次将此for h in teamsdf)插入==None中,在什么时候失败了,因为没有{{1} }。

答案 1 :(得分:0)

如果我了解您的代码,则您尝试遍历teams列表,并将其统计信息附加到数据框(如果要附加统计信息)。您正在将数据帧传递给teamStats函数,然后让它执行附加操作并返回到新的数据帧,在循环中将其设置为df

这不一定是错误的,但是我更希望该函数返回要附加的数据(如果有数据),并且附加将在外部循环中完成。我认为这样做会更清洁并且更不会出错。

考虑到这一点,我将这样重写您的代码:

teams = ["KC", "NYJ", "ATL", "BAL", "PIT", "ARI", "JAX", "OAK",
         "PHI", "IND", "SEA", "CAR", "NYG", "NO", "MIA", "TB", "LAC"]
df = pd.DataFrame(columns=["Home", "Away", "Win", "hRushYds", "hPassYds",
                           "hPuntAvg", "hPenYds", "aRushYds", "aPassYds",
                           "aPuntAvg", "aPenYds", "hScore", "aScore"])


def team_stats(h):
    game = nflgame.one(2017, 1, h, h)
    if game is not None:
        return {
            "Home": game.home,
            "Away": game.away,
            "Win": int(game.home == game.winner),  # int(True) = 1, int(False) = 0
            "hPassYds": game.stats_home.passing_yds,
            "aPassYds": game.stats_away.passing_yds,
            "hScore": game.score_home,
            "aScore": game.score_away,
            "hRushYds": game.stats_home.rushing_yds,
            "aRushYds": game.stats_away.rushing_yds,
            "hPenYds": game.stats_home.penalty_yds,
            "aPenYds": game.stats_away.penalty_yds,
            "hPuntAvg": game.stats_home.punt_avg,
            "aPuntAvg": game.stats_away.punt_avg,
        }
    return None


for h in teams:
    stats = team_stats(h)
    if stats is not None:
        df = df.append(stats, ignore_index=True)
df

如您所见,team_stats函数返回要追加的数据(如果有数据),然后循环检查是否需要追加数据。我更喜欢这种方法,因为这样一来,函数不会更改任何外部数据(未在函数中本地定义的变量或数据结构),因此您出错的可能性较小,因为您忘记了返回data游戏为None(请参阅kawillzocken的答案)。

关于pythonic代码的最后两个注释:

  1. 如果在特定情况下函数返回None,则即使编写return None或使函数到达其主体结尾,也应显式编写return,即使获得相同的结果。这样,您显然想返回None,这可能有助于您发现该错误。在不应该返回任何内容的函数(无效函数)中使用其他方式。
  2. 根据pep8,在python中,更常见的做法是在small_letters_with_underscores_as_spaces中编写函数名称(以及变量)。因此,写team_stats而不是teamStats更为常规。当然,这是个人喜好,但我认为遵守约定是一种好习惯。