我正在使用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'))
如果有人能帮我。。。 谢谢大家:)
您可以根据需要使用单独的函数来生成每条记录:
相关问题 更多 >
编程相关推荐