使用Pandas Python 3将列表转换为数据框。
使用Pandas Python 3将列表转换为数据框。
此问题已经有答案了:
我正在尝试将列表中的字典转换为具有键作为列名的数据框。以下是示例数据。
df = [{'id': '755', 'player_name': 'Jamie Vardy', 'games': '35', 'time': '3034', 'goals': '23', 'xG': '18.903537318110466', 'assists': '5', 'xA': '6.3682975601404905', 'shots': '89', 'key_passes': '32', 'yellow_cards': '3', 'red_cards': '0', 'position': 'F S', 'team_title': 'Leicester', 'npg': '19', 'npxG': '15.097693115472794', 'xGChain': '21.02660731226206', 'xGBuildup': '1.7243406660854816'}, {'id': '318', 'player_name': 'Pierre-Emerick Aubameyang', 'games': '36', 'time': '3143', 'goals': '22', 'xG': '16.352623080834746', 'assists': '3', 'xA': '4.492486916482449', 'shots': '93', 'key_passes': '26', 'yellow_cards': '3', 'red_cards': '1', 'position': 'F M S', 'team_title': 'Arsenal', 'npg': '20', 'npxG': '14.830358987674117', 'xGChain': '19.964282035827637', 'xGBuildup': '5.339657470583916'}]
我可以像df[0]
这样调用每个字典,以及用df[0].keys()
作为键。
我使用以下代码来转换为数据框。
cols = list (df[0].keys()) df_new = pd.DataFrame.from_dict(df[0], orient='index', columns = cols )
它给我抛出了错误:ValueError: Shape of passed values is (18, 1), indices imply (18, 18)
有人能给我建议吗?
admin 更改状态以发布 2023年5月22日
据我所知,DataFrame构造函数应该能够胜任:
out = pd.DataFrame(df)
输出:
id player_name games time goals xG \ 0 755 Jamie Vardy 35 3034 23 18.903537318110466 1 318 Pierre-Emerick Aubameyang 36 3143 22 16.352623080834746 assists xA shots key_passes yellow_cards red_cards \ 0 5 6.3682975601404905 89 32 3 0 1 3 4.492486916482449 93 26 3 1 position team_title npg npxG xGChain \ 0 F S Leicester 19 15.097693115472794 21.02660731226206 1 F M S Arsenal 20 14.830358987674117 19.964282035827637 xGBuildup 0 1.7243406660854816 1 5.339657470583916
这将创建一个形状为(2, 18)的DataFrame。
如果你想让字典的键作为索引,一种选择是将df
转换为字典并传递给DataFrame.from_dict
:
out = pd.DataFrame(dict(enumerate(df)))
这将产生一个形状为(18, 2)的DataFrame。