带有嵌套列表的字典到数据框

时间:2018-07-04 00:36:40

标签: python python-3.x pandas

我目前有一本带有一些嵌套列表的字典,这有点混乱:

table = {"name":"ClosestDefender10ftPlusShooting", "headers":["PLAYER_ID","PLAYER_NAME_LAST_FIRST","SORT_ORDER","GP","G", "CLOSE_DEF_DIST_RANGE","FGA_FREQUENCY","FGM","FGA","FG_PCT","EFG_PCT","FG2A_FREQUENCY","FG2M","FG2A","FG2_PCT","FG3A_FREQUENCY","FG3M","FG3A","FG3_PCT"], "rowSet":[[2544,"James, LeBron",1,6,2,"0-2 Feet - Very Tight",0.014,0,0.33,0,0,0.007,0,0.17,0,0.007,0,0.17,0],[2544,"James, LeBron",2,6,6,"2-4 Feet - Tight",0.144,0.83,3.5,0.238,0.31,0.082,0.33,2,0.167,0.062,0.5,1.5,0.333],[2544,"James, LeBron",3,6,5,"4-6 Feet - Open",0.192,2.17,4.67,0.464,0.571,0.103,1.17,2.5,0.467,0.089,1,2.17,0.462],[2544,"James, LeBron",4,6,6,"6+ Feet - Wide Open",0.11,1.33,2.67,0.5,0.656,0.041,0.5,1,0.5,0.068,0.83,1.67,0.5]]}

并使用大熊猫,我希望将其放入一个表中,其中标题是headers列表中的所有值,并且每一行都以rowSet中的值命名,就像表一样此处显示:http://stats.nba.com/player/2544/shots-dash/?sort=G&dir=-1

我已经尝试过类似df = pd.DataFrame(list(table.items()))之类的事情,但是它们都返回了非常混乱的表,所以我不确定如何处理该字典的嵌套性质。

其余代码为:

import requests
import pandas as pd

url = 'http://stats.nba.com/stats/playerdashptshots?DateFrom=&DateTo=&GameSegment=&LastNGames=6&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PerMode=PerGame&Period=0&PlayerID=2544&Season=2017-18&SeasonSegment=&SeasonType=Playoffs&TeamID=0&VsConference=&VsDivision='

response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
table = response.json()['resultSets'][5]
data_headers = table.get('headers')

有没有办法在几行中做到这一点,还是我需要走一条更手动的路线?

1 个答案:

答案 0 :(得分:2)

pipe

输出:

df=pd.DataFrame(data=table['rowSet'], columns=table['headers'])