我有這個函式,它接收一個 JSON,將其轉換為 pandas 資料幀,進行計算并嘗試以正確的 json 形式回傳它。
函式如下所示:
def run(data):
try:
start_time = datetime.datetime.now()
ret_columns = ["operat_flight_nbr", "schd_leg_dep_dt", \
"schd_leg_dep_tm", "dep_airprt_cd", "predictions"]
df = pd.DataFrame.from_records(json.loads(data)["data"])
predictions = predict(df)
df["predictions"] = predictions
elapsed_time_ms = (datetime.datetime.now() - start_time).total_seconds() * 1000
return {"data" : json.loads(df[ret_columns].to_json(date_format="iso")), "predictions" : predictions, "elapsed_time_ms" : elapsed_time_ms }
這是當前不受歡迎的輸出:
{
"data": {
"operat_flight_nbr": {
"0": 2825,
"1": 3701
},
"schd_leg_dep_dt": {
"0": "2021-06-04",
"1": "2021-08-09"
},
"schd_leg_dep_tm": {
"0": "09:41:00",
"1": "13:03:00"
},
"dep_airprt_cd": {
"0": "CLT",
"1": "MYT"
},
"predictions": {
"0": 18.1041783139,
"1": 2.947184921
}
},
"predictions": [
18.104178313869596,
2.947184920966057
],
"elapsed_time_ms": 59.61000000000001
}
這是所需的輸出:
{
"data": [
{
"operat_flight_nbr": 2825
"schd_leg_dep_dt": "2021-06-04"
"schd_leg_dep_tm": "09:41:00"
"dep_airprt_cd": "CLT",
"predictions": 18.1041783139
},
{
"operat_flight_nbr": 3701
"schd_leg_dep_dt": "2021-08-09"
"schd_leg_dep_tm": "13:03:00"
"dep_airprt_cd": "MYT",
"predictions" : 2.947184921
}
],
"predictions": [
18.104178313869596,
2.947184920966057
],
"elapsed_time_ms": 59.61000000000001
}
我想我需要在某處使用 json.dumps() ,但是當我洗掉 .to_json() 函式時,它的日期格式錯誤。
uj5u.com熱心網友回復:
添加orient='records'到您的to_json()通話中:
return {"data" : json.loads(df[ret_columns].to_json(date_format="iso", orient="records")), "predictions" : predictions, "elapsed_time_ms" : elapsed_time_ms }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/444537.html
上一篇:將CSV轉換為JSON,拆分為x個JSON檔案并將結果存盤到minio存盤桶
下一篇:如果滿足條件,熊貓填寫組
