【问题标题】:Convert Nested JSON into Dataframe将嵌套 JSON 转换为数据框
【发布时间】:2019-07-08 18:28:04
【问题描述】:

我有一个嵌套的 JSON,如下所示。我想将其转换为熊猫数据框。作为其中的一部分,我还需要只解析权重值。我不需要这个单元。

我还希望将数值从字符串转换为数字。

任何帮助将不胜感激。我对python比较陌生。谢谢。

JSON 示例:

{'id': '123', 'name': 'joe', 'weight': {'number': '100', 'unit': 'lbs'}, 
'gender': 'male'}

下面的示例输出:

id     name    weight    gender
123    joe     100       male

【问题讨论】:

    标签: python json pandas numpy dataframe


    【解决方案1】:

    使用“ from pandas.io.json import json_normalize”。

    id     name    weight.number  weight.unit  gender
    123    joe     100              lbs        male
    

    【讨论】:

      【解决方案2】:

      这样的事情应该可以解决问题:

      json_data = [{'id': '123', 'name': 'joe', 'weight': {'number': '100', 'unit': 'lbs'}, 'gender': 'male'}]
      # convert the data to a DataFrame
      df = pd.DataFrame.from_records(json_data)
      # conver id to an int
      df['id'] = df['id'].apply(int)
      # get the 'number' field of weight and convert it to an int
      df['weight'] = df['weight'].apply(lambda x: int(x['number']))
      df
      

      【讨论】:

        【解决方案3】:

        如果你想丢弃重量单位,只需将 json 展平即可:

        temp = {'id': '123', 'name': 'joe', 'weight': {'number': '100', 'unit': 'lbs'}, 'gender': 'male'}
        temp['weight'] = temp['weight']['number']
        

        然后把它变成一个数据框:

        pd.DataFrame(temp)
        

        【讨论】:

          猜你喜欢
          • 2017-03-21
          • 2020-12-16
          • 1970-01-01
          • 1970-01-01
          • 2019-11-24
          • 1970-01-01
          • 2022-01-21
          相关资源
          最近更新 更多