Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用数组中的特定列将数据输出到JSON_Json_Python 3.x_Pandas_Dataframe - Fatal编程技术网

如何使用数组中的特定列将数据输出到JSON

如何使用数组中的特定列将数据输出到JSON,json,python-3.x,pandas,dataframe,Json,Python 3.x,Pandas,Dataframe,我需要逐行将一些结果从Pandas数据帧输出到JSON。我已经整理好了导出,效果很好,它是将某些列放入数组的精细细节。比如说 Id customerId baseValue targetValue 1客户1482306 2客户2 723 420 3客户3 279 161 4客户4162774 对于Id 1,我需要以的样式导出 {“Id”:“1”, “customerId”:“Customer1”, “结果”:[{“基本值”:482}, {“targetValue”:306} ] } 我被困在

我需要逐行将一些结果从Pandas数据帧输出到JSON。我已经整理好了导出,效果很好,它是将某些列放入数组的精细细节。比如说

Id customerId baseValue targetValue
1客户1482306
2客户2 723 420
3客户3 279 161
4客户4162774
对于Id 1,我需要以的样式导出

{“Id”:“1”,
“customerId”:“Customer1”,
“结果”:[{“基本值”:482},
{“targetValue”:306}
]
}
我被困在这一点上:

“结果”:[{“baseValue”:482},
{“targetValue”:306}
]
有什么建议吗

谢谢

您是否尝试过:

df.to_json(orient=“index”) 您是否尝试过:

df.to_json(orient=“index”)
您可以尝试以下方法在数据框中创建“结果”列:

df.assign(results = df.apply(lambda x: [x[['baseValue','targetValue']].to_dict()], axis=1)).drop(['baseValue','targetValue'], axis=1).to_dict(orient='records')
输出:

[{'Id': 1,
  'customerId': 'Customer1',
  'results': [{'baseValue': 482, 'targetValue': 306}]},
 {'Id': 2,
  'customerId': 'Customer2',
  'results': [{'baseValue': 723, 'targetValue': 420}]},
 {'Id': 3,
  'customerId': 'Customer3',
  'results': [{'baseValue': 279, 'targetValue': 161}]},
 {'Id': 4,
  'customerId': 'Customer4',
  'results': [{'baseValue': 162, 'targetValue': 774}]}]

您可以尝试以下方法在数据框中创建“结果”列:

df.assign(results = df.apply(lambda x: [x[['baseValue','targetValue']].to_dict()], axis=1)).drop(['baseValue','targetValue'], axis=1).to_dict(orient='records')
输出:

[{'Id': 1,
  'customerId': 'Customer1',
  'results': [{'baseValue': 482, 'targetValue': 306}]},
 {'Id': 2,
  'customerId': 'Customer2',
  'results': [{'baseValue': 723, 'targetValue': 420}]},
 {'Id': 3,
  'customerId': 'Customer3',
  'results': [{'baseValue': 279, 'targetValue': 161}]},
 {'Id': 4,
  'customerId': 'Customer4',
  'results': [{'baseValue': 162, 'targetValue': 774}]}]