【问题标题】:Define specific json export format of pandas dataframe定义pandas dataframe的具体json导出格式
【发布时间】:2020-01-15 15:35:48
【问题描述】:

我需要将我的 DF 导出为特定的 JSON 格式,但我正在努力以正确的方式对其进行格式化。

我想创建一个带有 shop_details 的子部分,如果商店已知,它会显示商店的城市和位置,否则应该留空。

我的 DF 代码:

from pandas import DataFrame

Data = {'item_type': ['Iphone','Computer','Computer'],
        'purch_price': [1200,700,700],
        'sale_price': [1150,'NaN','NaN'],
        'city': ['NaN','Los Angeles','San Jose'],
        'location': ['NaN','1st street', '2nd street']
        }

DF 看起来像这样:

  item_type  purch_price sale_price         city    location
0    Iphone         1200       1150          NaN         NaN
1  Computer          700        NaN  Los Angeles  1st street
2  Computer          700        NaN     San Jose  2nd street

输出格式应如下所示:

[{
    "item_type": "Iphone",
    "purch_price": "1200",
    "sale_price": "1150",
    "shop_details": []
  },
  {
    "item_type": "Computer",
    "purch_price": "700",
    "sale_price": "600",
    "shop_details": [{
        "city": "Los Angeles",
        "location": "1st street"
      },
      {
        "city": "San Jose",
        "location": "2nd street"
      }
    ]
  }
]

【问题讨论】:

  • 你能展示你为解决这个问题所做的努力吗?
  • 嗨@harvpan!我还没有找到接近的东西。我已经通过 SO 和谷歌搜索,并搞乱了以下两个来源(这似乎最接近我需要的)但不幸的是无济于事:linklink 我觉得我应该按各个列分组,但可以不知道到底是什么..

标签: python json pandas dataframe export


【解决方案1】:
import json

df = df.fillna('')

def shop_details(row):
    if row['city'] != '' and row['location'] !='':
        return [{'city': row['city'], 'location': row['location']}]
    else:
        return []

df['shop_details'] = df.apply(lambda row: shop_details(row), axis = 1)

df = df.drop(['city', 'location'], axis = 1)

json.dumps(df.to_dict('records'))

唯一的问题是我们不按 item_type 分组,但你应该做一些工作;)

【讨论】:

    【解决方案2】:

    您可以执行以下操作来实现您的输出。谢谢

    from pandas import DataFrame
    
    Data = {'item_type': ['Iphone','Computer','Computer'],
            'purch_price': [1200,700,700],
            'sale_price': [1150,'NaN','NaN'],
            'city': ['NaN','Los Angeles','San Jose'],
            'location': ['NaN','1st street', '2nd street']
            }
    
    df = DataFrame(Data, columns= ['item_type', 'purch_price', 'sale_price', 'city','location' ])
    
    Export = df.to_json ('path where you want to export your json file')
    

    【讨论】:

    • 感谢您的回答,不幸的是,这并没有给我想要的输出。
    猜你喜欢
    • 2016-06-12
    • 2016-03-24
    • 1970-01-01
    • 2021-10-16
    • 2017-08-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多