【发布时间】:2019-01-21 11:48:12
【问题描述】:
我尝试从 JSON 文件创建 DataFrame。
我有一个名为“Series_participants”的列表,其中包含此 JSON 文件的一部分。当我打印它时,我的列表看起来像 thise。
participantId 1
championId 76
stats {'item0': 3265, 'item2': 3143, 'totalUnitsHeal...
teamId 100
timeline {'participantId': 1, 'csDiffPerMinDeltas': {'1...
spell1Id 4
spell2Id 12
highestAchievedSeasonTier SILVER
dtype: object
<class 'list'>
在我尝试将此列表转换为这样的 DataFrame 之后
pd.DataFrame(Series_participants)
但 pandas 使用“stats”和“timeline”的值作为 DataFrame 的索引。我希望有自动索引范围 (0, ..., n)
编辑 1:
participantId championId stats teamId timeline spell1Id spell2Id highestAchievedSeasonTier
0 1 76 3265 100 NaN 4 12 SILVER
我想要一个带有“stats”和“timeline”列的数据框,其中包含它们在系列显示中的值的字典。
我的错误是什么?
编辑2:
我尝试手动创建 DataFrame,但 pandas 没有考虑我的选择,最终采用了 Series 的“stats”键的索引。
这是我的代码:
for j in range(0,len(df.participants[0])):
for i in range(0,len(df.participants[0][0])):
Series_participants = pd.Series(df.participants[0][i])
test = {'participantId':Series_participants.values[0],'championId':Series_participants.values[1],'stats':Series_participants.values[2],'teamId':Series_participants.values[3],'timeline':Series_participants.values[4],'spell1Id':Series_participants.values[5],'spell2Id':Series_participants.values[6],'highestAchievedSeasonTier':Series_participants.values[7]}
if j == 0:
df_participants = pd.DataFrame(test)
else:
df_participants.append(test, ignore_index=True)
双循环是解析我的JSON文件的所有“参与者”。
最后编辑:
我用下面的代码实现了我想要的:
for i in range(0,len(df.participants[0])):
Series_participants = pd.Series(df.participants[0][i])
df_test = pd.DataFrame(data=[Series_participants.values], columns=['participantId','championId','stats','teamId','timeline','spell1Id','spell2Id','highestAchievedSeasonTier'])
if i == 0:
df_participants = pd.DataFrame(df_test)
else:
df_participants = df_participants.append(df_test, ignore_index=True)
print(df_participants)
感谢大家的帮助!
【问题讨论】:
标签: python json python-3.x pandas dataframe