如何将带整数键的嵌套JSON转换为Pandas DataFrame?
将嵌套字典转换为Pandas DataFrame的正确姿势
嘿,我懂你的困扰——用pd.json_normalize()的时候,外层的整数键居然被当成列了,完全不是你想要的效果对吧?其实问题出在json_normalize()的预期输入格式上,它默认处理的是字典组成的列表,而你的数据是一个以整数为键、每个值对应一行数据的大字典,所以才会搞反行列。
下面给你两种简单的解决方法,选哪种都可以:
方法1:用pd.json_normalize()配合字典值列表
先把外层字典里的所有内层字典提取出来变成一个列表,再传给json_normalize(),这样它就能正确识别每行数据,把内层的键作为列:
import pandas as pd # 你的原始数据 data = { 0: {'Geographical information': 'Sweden', 'Geography': 'mentioned', 'Time': 'not_relevant', 'annotation': 'quantitative_precise', 'claim': ' “"', 'label': 'Mostly true', 'text': 'Swedish.'}, 1: {'Geographical information': 'Italy', 'Geography': 'mentioned', 'Time': 'unclear', 'annotation': 'quantitative_precise', 'claim': '', 'label': 'Mostly false', 'text': '.'}, 2: {'Geography': 'not_relevant', 'Time': 'unclear', 'annotation': 'quantitative_vague', 'claim': ' "”', 'label': 'False', 'text': '.'}, 3: {'Geographical information': 'France', 'Geography': 'mentioned', 'Time': 'not_relevant', 'annotation': 'qualitative', 'claim': ' ', 'label': 'Mostly false', 'text': '.'} } # 提取所有内层字典组成列表 records = list(data.values()) # 转换为DataFrame df = pd.json_normalize(records) # 如果想要保留原来的整数作为行索引,加上这一行 df.index = data.keys()
方法2:更直接的pd.DataFrame.from_dict()
这个方法更省心,只需要指定orient='index',就会自动把外层的整数键作为行索引,内层的键作为列:
import pandas as pd # 同样用你的原始data df = pd.DataFrame.from_dict(data, orient='index') # 要是不需要原来的整数索引,想换成默认的0、1、2...,可以重置索引: # df = df.reset_index(drop=True)
两种方法都能得到你想要的结果:内层字典的键(比如Geographical information)作为列,外层的整数作为行索引(或者默认的行号)。
如果之后遇到更复杂的嵌套JSON结构,json_normalize()会更灵活;但针对你现在的情况,from_dict()的方法更简洁直接~
内容的提问来源于stack exchange,提问作者corvusMidnight
相关产品推荐
相关产品推荐

