【问题标题】:Convert pandas dataframe to json将熊猫数据框转换为 json
【发布时间】:2021-08-21 07:51:00
【问题描述】:

我有一个熊猫数据框:

Df = pd.DataFrame({ 'FirstId': 123,
                   'SecondId': 345,
                   'ThirdId': 678,
                   'country' : 'Gambia',
                   'type' : 'Major',
                   'Version' : 3,
                   'original': 'NotOriginal',
                   'Score1': 12.3,
                  'Score2': 30.4 
                           })

我想要的 json 应该是这样的:

{
  "FirstId": 123,
  "SecondId": 345,
  "ThirdId": 678,
  "country": "Gambia",
  "algorithmType": {
    "type": "Major", 
    "Version": 3
  },
  "original": "NotOriginal",
  "Score1": 12.3,
  "Score2": 30.4
}

我试过了:

js = (Df.groupby(['FirstId','SecondId','ThirdId','country','original', 'Score1', 'Score2'])
             .apply(lambda x: x[['type','Version']].to_dict('records'))
              .reset_index()
             .rename(columns={0:'algorithmType'})
             .to_json(orient='records', lines=True))


print(json.dumps(json.loads(js), indent=2))

我的尝试没有给出我想要的顺序,它把 'algorithmType' 作为一个数组,而不是我想要的一个对象。

【问题讨论】:

    标签: arrays json python-3.x pandas


    【解决方案1】:

    如果你有这样的 df:

       FirstId  SecondId  ThirdId country   type  Version     original  Score1  \
    0      123       345      678  Gambia  Major        3  NotOriginal    12.3   
    
       Score2  
    0    30.4  
    

    尝试:

    json_output = df.assign(algorithmType=df[['type', 'Version']].to_dict(
        'records')).drop(['type', 'Version'], 1).to_dict('records')
    

    输出:

    [{'FirstId': 123,
      'SecondId': 345,
      'ThirdId': 678,
      'country': 'Gambia',
      'original': 'NotOriginal',
      'Score1': 12.3,
      'Score2': 30.4,
      'algorithmType': {'type': 'Major', 'Version': 3}}]
    

    更新答案:

    json_output = df.assign(algorithmType=df[['type', 'Version']].to_dict(
        'records')).drop(['type', 'Version'], 1)[['FirstId', 'SecondId', 'ThirdId', 'country', 'algorithmType',
                                                  'original', 'Score1', 'Score2']].to_dict('records')
    

    输出:

    [{'FirstId': 123,
      'SecondId': 345,
      'ThirdId': 678,
      'country': 'Gambia',
      'algorithmType': {'type': 'Major', 'Version': 3},
      'original': 'NotOriginal',
      'Score1': 12.3,
      'Score2': 30.4}]
    

    【讨论】:

    • 您的解决方案中是否可以在“国家”之后使用“算法类型”?
    • @user1783739 完成。
    猜你喜欢
    • 2018-08-25
    • 2023-03-18
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多