如何使用多个应用于Pandas

2024-04-25 01:18:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pandas和Python将Excel导出为JSON。这是我使用这个lib和python的第一天:)

Excel文件: My excel datas

或数据帧:

     DATA1  NAME CLIENT  PHONE CLIENT  NAME BOSS  PHONE BOSS
0    123    JOHN         DOE           KING       KING

我正在尝试这样一个JSON:

[
  {
    "DATA1": 123,
    "CLIENT": [
      {
        "NAME CLIENT": "John",
        "PHONE CLIENT": "Doe"
      }
    ],
    "BOSS": [
      {
        "NAME BOSS": "King",
        "PHONE BOSS": "King"
      }
    ]
  }
]

当我尝试获取第一个json数组时没有问题,我使用的是:

df.groupby(["DATA1"], as_index=False)
  .apply(lambda x: x[['NAME CLIENT', 'PHONE CLIENT']].to_dict('r'))
   .reset_index()
   .rename(columns={0: 'CLIENT'})
   .to_json(path_or_buf='output_path.json', orient='records'))

但是如果我试图同时得到两个数组,它就不起作用了。。。我尝试执行多个apply或agg函数,但它不起作用,我不知道在哪里必须使用dict函数:

 df.groupby(["DATA1"], as_index=False)
   .agg({'CLIENT' : lambda x: x[['NAME CLIENT', 'PHONE CLIENT']],
     'BOSS' : lambda x: x[['NAME BOSS', 'PHONE BOSS']]})
   .reset_index()
   .to_json(path_or_buf='output_path.json', orient='records'))

如果有人能帮我。。。 谢谢大家:)


Tags: topathlambdanameclientjsonindexphone
1条回答
网友
1楼 · 发布于 2024-04-25 01:18:17

您可以根据需要使用单独的函数来生成每条记录:

def f( df ):
    return { 'CLIENT': df[ ['NAME CLIENT', 'PHONE CLIENT'] ],
             'BOSS': df[ ['NAME BOSS', 'PHONE BOSS'] ], 
             'DATA1': df[ 'DATA1' ].values[0]
           }

df.groupby("DATA1", as_index=False).apply( f ).to_json(path_or_buf='output_path.json', orient='records')

相关问题 更多 >