【问题标题】:Create a nested JSON out of a pandas dataframe从 pandas 数据框创建嵌套 JSON
【发布时间】:2020-12-22 02:08:57
【问题描述】:
Year    temp    Name        DateTime
1950    0       De Bilt     010100
1951    1       De Bilt     010100
1950    2       De Bilt     010101
1951    3       De Bilt     010101
1950    0       Arcen       010100
1951    1       Arcen       010100

我有这个数据框 (df_stations),并想用它创建一个 JSON,格式如下:

{
  "De Bilt": {
    "010100": {
      "1950": {
        "temp": 0
      },
      "1951": {
        "temp": 1
      }
    },
    "010101": {
      "1950": {
        "temp": 2
      },
      "1951": {
        "temp": 3
      }
    }
  },
  "Arcen": {
    "010100": {
      "1950": {
        "temp": 0
      },
      "1951": {
        "temp": 1
      }
    },
...

但是,以下代码没有给我正确的结果:

def f(x):
    return (dict({k:v for k,v in zip(x.DateTime,x.Year)},**{'temp':x.temp.iloc[0]}))
(
    df_stations.groupby(['Name','DateTime','Year'])
      .apply(f)
      .groupby(level=0)
      .apply(lambda x: x.tolist())
      .to_dict()
)

有人可以帮我解决这个问题吗?非常感谢!

【问题讨论】:

  • 你能举一个例子,数据框中的输入值对应于 JSON 中的输出值吗?当你有De BiltArcen 在输出而不是输入,Voorschoten 在输入而不是输出时,要准确理解你的目标有点困难。
  • 感谢@MatějRačinský 的评论,我已更新数据框以与 JSON 相对应。

标签: python json pandas nested


【解决方案1】:

让我们试试双组:

{k: {v:d.set_index('Year').to_dict('i') for v,d in g.drop('DateTime',axis=1).groupby(g['DateTime'])}
     for k,g in df.drop('Name',axis=1).groupby(df['Name'])
}

输出:

{'Arcen':   {10100: {1950: {'temp': 0}, 1951: {'temp': 1}}},
 'De Bilt': {10100: {1950: {'temp': 0}, 1951: {'temp': 1}},
             10101: {1950: {'temp': 2}, 1951: {'temp': 3}}
            }
}

但是,由于数据嵌套严重,我确实认为这不是最好的 JSON 格式。

【讨论】:

    【解决方案2】:
    def f(x):
        return {level1: {level2: b.xs(level1).xs(level2).to_dict() for level2 in b.xs(level1).index.levels[0] if level2 in b.xs(level1).index.get_level_values(0)} for level1 in b.index.levels[0]}
    
    df_stations.groupby(['Name','DateTime','Year']).apply(f)[0]
    

    会给你结果

    {'Arcen': {'010100': {1950: {'temp': 0}, 1951: {'temp': 1}}},
     'De Bilt': {'010100': {1950: {'temp': 0}, 1951: {'temp': 1}},
      '010101': {1950: {'temp': 2}, 1951: {'temp': 3}}}}
    

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2019-11-24
      • 1970-01-01
      • 2022-06-13
      • 2020-01-21
      • 2018-06-01
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      相关资源
      最近更新 更多