【问题标题】:flatten a deep json structure with jq for pandas使用 jq 为 pandas 展平深层 json 结构
【发布时间】:2014-04-06 17:31:53
【问题描述】:

我正在尝试将 JSON 文件展平为 pandas 数据框,并找到了解决方案 here。在我的例子中,JSON 有很多不同的属性,以至于手动为每个字段拼出规则似乎很乏味。不是可以自动展平 JSON 文件中的每个属性吗?

【问题讨论】:

  • 可能有助于举一个玩具例子

标签: jquery python json pandas


【解决方案1】:

我刚刚做了一些东西来解决类似的问题。这可能不适用于您的情况,但也许您可以采取类似的方法。

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.")

【讨论】:

  • 它对我不起作用,但这对其他人来说可能是一个很好的答案。 (在我的情况下,dicts 可以有不同的深度)。我终于手工做了很多索引工作,但现在我有一个看起来和你的有点相似的工作副本。
猜你喜欢
  • 1970-01-01
  • 2020-11-21
  • 2021-06-25
  • 2021-12-20
  • 1970-01-01
  • 2022-01-13
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多