python - 带有嵌套列表的字典到数据框
问题描述
我目前有一本带有一些嵌套列表的字典,有点乱:
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]]}
并使用 pandas 我想将它放入一个表中,其中我的标题是headers
列表中的所有值,并且每一行都以中的值命名rowSet
,如下所示的表:http: //stats.nba.com/播放器/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')
有什么办法可以在几行中做到这一点,还是我需要走一条更手动的路线?
解决方案
df=pd.DataFrame(data=table['rowSet'], columns=table['headers'])
输出:
PLAYER_ID PLAYER_NAME_LAST_FIRST SORT_ORDER GP G CLOSE_DEF_DIST_RANGE \
0 2544 James, LeBron 1 6 2 0-2 Feet - Very Tight
1 2544 James, LeBron 2 6 6 2-4 Feet - Tight
2 2544 James, LeBron 3 6 5 4-6 Feet - Open
3 2544 James, LeBron 4 6 6 6+ Feet - Wide Open
FGA_FREQUENCY FGM FGA FG_PCT EFG_PCT FG2A_FREQUENCY FG2M FG2A \
0 0.014 0.00 0.33 0.000 0.000 0.007 0.00 0.17
1 0.144 0.83 3.50 0.238 0.310 0.082 0.33 2.00
2 0.192 2.17 4.67 0.464 0.571 0.103 1.17 2.50
3 0.110 1.33 2.67 0.500 0.656 0.041 0.50 1.00
FG2_PCT FG3A_FREQUENCY FG3M FG3A FG3_PCT
0 0.000 0.007 0.00 0.17 0.000
1 0.167 0.062 0.50 1.50 0.333
2 0.467 0.089 1.00 2.17 0.462
3 0.500 0.068 0.83 1.67 0.500