[英]How to export pandas dataframe into json and retain original datetime format?
我正在處理數據集,並應用to_json()方法將 pandas dataframe 導出到 json 文件中。 然后我將使用這個 json 文件上傳到 MongoDB。 但是我意識到日期時間格式已轉換為紀元時間戳。 如何在導出到 JSON 文件以及將 json 文件上傳到 MongoDB 時保留日期時間格式? 另外,我不希望 json output 中的 null 字段。
東風:
user_id datetime
0 69490717 [{'checkin_date': 2021-02-01 00:00:00}]
1 67125777 [{'checkin_date': 2021-02-01 00:00:00}]
2 62747294 NaN
3 63216896 [{'checkin_date': 2021-02-01 00:00:00}]
4 51466797 [{'checkin_date': 2021-01-31 00:00:00}]
... ... ...
96 82758550 NaN
97 44662827 NaN
98 36376189 [{'checkin_date': 2021-01-18 00:00:00}]
99 71910948 [{'checkin_date': 2021-01-18 00:00:00}, {'checkout_date': 2021-01-20 00:00:00}]
100 54620533 NaN
json output 的片段:
[{"user_id":62507249,"datetime":[{"checkin_date":1612051200000},{"checkout_date":1612051200000}]},
{"user_id":69546481,"datetime":[{"checkin_date":1612051200000}]}, ......]
下面是我轉換為 json 的代碼:
jsonresult = df.T.apply(lambda row: row[~row.isnull()].to_json())
json_wrapped = "[%s]" % ",".join(jsonresult)
# write JSON to file
with open('jsonresult.json', 'w') as f:
f.write(json_wrapped)
您需要使用Series.astype
將datetime
時間列轉換為string
:
df['datetime'] = df['datetime'].astype(str)
此外,無需將其轉換為json
的代碼。 您可以執行以下操作:
jsonresult = df.to_json(orient='records')
我認為您需要 DataFrame.to_json 中date_format='iso'
參數,並且可以使用DataFrame.to_json
刪除具有缺失值的DataFrame.dropna
:
a = [{"user_id":1,"datetime":[{"checkin_date":pd.Timestamp('2021-02-01 00:00:00')},
{"checkout_date":pd.Timestamp('2021-02-01 00:00:00')}]},
{"user_id":2,"datetime":[{"checkin_date":pd.Timestamp('2021-02-01 00:00:00')}]},
{"user_id":4,"datetime": np.nan}]
df = pd.DataFrame(a)
print (df)
user_id datetime
0 1 [{'checkin_date': 2021-02-01 00:00:00}, {'chec...
1 2 [{'checkin_date': 2021-02-01 00:00:00}]
2 4 NaN
jsonresult = df.dropna(subset=['datetime']).to_json(date_format='iso', orient='records')
print (jsonresult)
[{"user_id":1,"datetime":[{"checkin_date":"2021-02-01T00:00:00.000Z"},
{"checkout_date":"2021-02-01T00:00:00.000Z"}]},
{"user_id":2,"datetime":[{"checkin_date":"2021-02-01T00:00:00.000Z"}]}]
dictresult = df.dropna(subset=['datetime']).to_dict(orient='records')
print (dictresult)
[{'user_id': 1, 'datetime': [{'checkin_date': Timestamp('2021-02-01 00:00:00')},
{'checkout_date': Timestamp('2021-02-01 00:00:00')}]},
{'user_id': 2, 'datetime': [{'checkin_date': Timestamp('2021-02-01 00:00:00')}]}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.