用jq为pandas扁平化深层JSON结构

0 投票
1 回答
833 浏览
提问于 2025-04-18 01:37

我正在尝试把一个JSON文件转换成pandas的数据框(dataframe),并找到了一个解决方案,具体可以在这里查看。在我的情况下,这个JSON文件有很多不同的属性,手动为每个字段写规则感觉太麻烦了。难道不可以自动把JSON文件里的每个属性都展开吗?

1 个回答

3

我刚刚做了一个东西来解决类似的问题。这可能不适合你的情况,但也许你可以尝试类似的方法。

def nested_dataframe(d):
    assert type(d) is dict  # may be a nested dict
    types = map(type, d.values())
    if dict not in types:
        # This is one un-nested dict. Make it a DataFrame.
        return DataFrame.from_dict({k: list([v]) for k, v in d.items()}, orient='index')
    if all([t is dict for t in types]):
        # This is a dict of dicts.
        # Call nested_dataframe on each item, and concatenate the results.
        return pd.concat([nested_dataframe(a) for a in d.values()], keys=d.keys())
    else:
        raise ValueError("This doesn't work on dicts with unequal depths.")

撰写回答