python - 使用 pandas 将两个不同的数据帧转换为一个 json 文件

标签 python json pandas

我的第一个数据框 df_gammask 看起来像这样:

    distance breakEvenDistance  min max
0   2.1178  2.0934  NaN         0.000955
1   2.0309  2.1473  0.000955    0.001041
2   1.9801  1.7794  0.001041    0.001124
3   1.9282  2.1473  0.001124    0.001199
4   1.8518  1.5885  0.001199    0.001259
5   1.8518  1.5151  0.001259    0.001319

我的第二个 df_gammabid:

distance    breakEvenDistance   min max
0   1.9999  1.9329  NaN         0.001034
1   1.9251  2.0670  0.001034    0.001118
2   1.8802  1.6758  0.001118    0.001193
3   1.8802  1.5956  0.001193    0.001252
4   1.7542  1.5181  0.001252    0.001317
5   1.7542  1.4541  0.001317    0.001374

我需要的是像这样的 json 文件:

{
  "buy": [
    {
      "distance": 0.6278,
      "breakEvenDistance": 0.6261,
      "max": 0.0031920626236615754
    },
    {
      "distance": 0.6224,
      "breakEvenDistance": 0.6199,
      "min": 0.0031920626236615754,
      "max": 0.003223405873670448
    },
    {
      "distance": 0.6202,
      "breakEvenDistance": 0.6142,
      "min": 0.003223405873670448,
      "max": 0.003253791039488344
    },
    {
      "distance": 0.6174,
      "breakEvenDistance": 0.6081,
      "min": 0.003253791039488344,
      "max": 0.003285709011703031}],


"sell": [
    {
      "distance": 0.8012,
      "breakEvenDistance": 0.8005,
      "max": 0.0024962095663052064
    },
    {
      "distance": 0.7996,
      "breakEvenDistance": 0.7939,
      "min": 0.0024962095663052064,
      "max": 0.002516799325547373
    },
    {
      "distance": 0.794,
      "breakEvenDistance": 0.7877,
      "min": 0.002516799325547373,
      "max": 0.0025370182220432014
    },
    {
      "distance": 0.7927,
      "breakEvenDistance": 0.7807,
      "min": 0.0025370182220432014,
      "max": 0.0025605480833123294
    }]

我知道有函数 pd.DataFrame.to_json 但它适用于一个数据帧,关于如何使用 2 个数据帧和上述格式执行此操作的任何线索?我必须合并它们吗? buy 端是 df_gammasksell 端是 dg_gammabid!谢谢

最佳答案

使用DataFrame.to_dict在嵌套字典理解中删除缺失值,然后创建 dictionary 并转换为 json:

import json
L1 = [{k: v for k, v in x.items() if pd.notnull(v)} for x in df_gammask.to_dict('r')]
L2 = [{k: v for k, v in x.items() if pd.notnull(v)} for x in df_gammabid.to_dict('r')]

with open('file.json', 'w') as file:
    json.dump({ "buy": L1, "sell": L2}, file)

关于python - 使用 pandas 将两个不同的数据帧转换为一个 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55119103/

相关文章:

python - 从 Pandas Groupby Dataframe 创建等高线图

python - 将 Python 2.x 文件(如对象)移植到 Python 3

python - 将我的设置更改为 DEBUG = False 后发生的错误

python - 无效请求状态 : oauth2 flask

javascript 错误 [jsonFlickrApi 未定义]

javascript - 替换 JSON 中的嵌套字符串

json - 如何在 TextMate、Emacs、BBEdit 或 Sublime Text 2 中缩进 JSON 数据?

python - Pandas dataframe.to_csv 文件行彼此不对齐

python - 为什么 Pandas 中有 datetime.datetime ?

python - 在 Pyramid 中使用 Mako 模板与 Google App Engine