将列表转换为DataFrame时,如何处理错误“'NoneType'对象没有属性'键'”

时间:2019-01-02 13:49:14

标签: python python-3.x dataframe web-scraping

尝试从列表创建数据框但出现错误 “'NoneType'对象没有属性'keys'”

import numpy as np
import pandas as pd
import requests
import json
from sklearn import preprocessing
from sklearn.preprocessing import OneHotEncoder

person = []
position = []
skaterstats = []
person = []
player_id = {}
 for game_id in range(2018020001, 2018020002, 1):
    url = 'https://statsapi.web.nhl.com/api/v1/game/{}/feed/live'.format(game_id)
    r = requests.get(url)
    game_data = r.json()

for homeaway in ['home','away']:
    player_dict = game_data.get('liveData').get('boxscore').get('teams').get(homeaway).get('skaters')
    player_id[homeaway] = player_dict

for homeaway in player_id:
    for playerID in player_id[homeaway]:
        play_dict_person = game_data.get('liveData').get('boxscore').get('teams').get(homeaway).get('players').get('ID' + str(playerID)).get('person')
        play_dict_position = game_data.get('liveData').get('boxscore').get('teams').get(homeaway).get('players').get('ID' + str(playerID)).get('position')
        play_dict_skaterstats = game_data.get('liveData').get('boxscore').get('teams').get(homeaway).get('players').get('ID' + str(playerID)).get('stats').get('skaterStats')
        person.append(play_dict_person)
        position.append(play_dict_position)
        skaterstats.append(play_dict_skaterstats)

df_person = pd.DataFrame(person).head()
df_position = pd.DataFrame(position).head()
df_skaterstats = pd.DataFrame(skaterstats).head()

----> 3 df_skaterstats = pd.DataFrame(skaterstats).head() 

AttributeError: 'NoneType' object has no attribute 'keys'

仅在此DataFrame上发生错误,我已经检查了路径是否正确以及全部。如果有任何指导,请链接至下面的API。

这是API:https://statsapi.web.nhl.com/api/v1/game/2017020002/feed/live

1 个答案:

答案 0 :(得分:1)

某些玩家没有统计信息,因此play_dict_skaterstats就是None。您可能需要更换

skaterstats.append(play_dict_skaterstats)

使用

if play_dict_skaterstats: 
    skaterstats.append(play_dict_skaterstats)

跳过这些情况

或者您可能需要为这种情况设置默认值,例如

if not play_dict_skaterstats:
    play_dict_skaterstats = {}
    play_dict_skaterstats['timeOnIce'] = None
    play_dict_skaterstats['assists'] = None
    ...
skaterstats.append(play_dict_skaterstats)