【发布时间】:2016-12-02 09:09:13
【问题描述】:
编辑:我做了很多努力,我现在正试图从我的 JSON 文件中解析出单列,而不是整行。但是,每当我尝试操纵我的 DataFrame 以获得我想要的结果时,我都会收到一个错误。
错误是: 第 52 行,在 df = pd.DataFrame.from_dict(mlbJson['stats_sortable_player']['queryResults']['name_display_first_last']) KeyError: 'name_display_first_last'
只有当我尝试添加另一个参数时才会发生这种情况,例如我取出 ['row'] 并添加 ['name_display_first_last'] 以获取每个玩家的名字和姓氏。如果我留在 ['row'] 中,它会编译,但会给我所有数据,我只想要某些 sn-ps。
任何帮助将不胜感激!谢谢。
import requests
import pandas as pd
from bs4 import BeautifulSoup
# Scraping data from MLB.com
target = [MLB JSON][1]
mlbResponse = requests.get(target)
mlbJson = mlbResponse.json()
# Placing response in variable
# Collecting data and giving it names in pandas
data = {'Team': team, 'Line': line}
# places data table format, frames the data
table = pd.DataFrame(data)
# Creates excel file named Scrape
writer = pd.ExcelWriter('Scrape.xlsx')
# Moves table to excel taking in Parameters , 'Name of DOC and Sheet on that Doc'
table.to_excel(writer, 'Lines 1')
#stats = {'Name': name, 'Games': games, 'AtBats': ab, 'Runs': runs, 'Hits': hits, 'Doubles': doubles, 'Triples': triples, 'HR': hr, 'RBI': rbi, 'Walks': walks, 'SB': sb}
df = pd.DataFrame.from_dict(mlbJson['stats_sortable_player']['queryResults']['row'])
df.to_excel(writer, 'Batting 2')
# Saves File
writer.save()
【问题讨论】:
标签: python json excel pandas beautifulsoup