【发布时间】:2014-04-06 17:31:53
【问题描述】:
我正在尝试将 JSON 文件展平为 pandas 数据框,并找到了解决方案 here。在我的例子中,JSON 有很多不同的属性,以至于手动为每个字段拼出规则似乎很乏味。不是可以自动展平 JSON 文件中的每个属性吗?
【问题讨论】:
-
可能有助于举一个玩具例子
我正在尝试将 JSON 文件展平为 pandas 数据框,并找到了解决方案 here。在我的例子中,JSON 有很多不同的属性,以至于手动为每个字段拼出规则似乎很乏味。不是可以自动展平 JSON 文件中的每个属性吗?
【问题讨论】:
我刚刚做了一些东西来解决类似的问题。这可能不适用于您的情况,但也许您可以采取类似的方法。
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.")
【讨论】: