简体   繁体   English

Python to_json 函数未将 DataFrame 以正确格式的日期字段转换为 Json

[英]Python to_json function not converting DataFrame to Json in proper format for Date Field

I am facing a problem in receiving correct date formatted data from the CSV using to_json function of pandas.我在使用 pandas 的 to_json 函数从 CSV 接收正确日期格式的数据时遇到问题。

import pandas as pd
import json

df = pd.read_csv("C:\\Users\\shubham\\Desktop\\Output\\MasterData.csv")
df1 = df.to_json(orient='records')
print(df1)

Current Output:-电流输出:-

[{"invoiceDate":"18\/08\/2019","amount":1140.87}]

I am expecting Output:- "invoiceDate":"18/08/2019"我期待输出:-“发票日期”:“18/08/2019”

I already tried to_json arguments:- date_format = "iso" double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None) , and replace is also not working (df.replace("/","")) .我已经尝试过 to_json 参数:- date_format = "iso" double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None) ,并且替换也不起作用(df.replace("/","")) .

Create dictionary and write to file with json.dump :创建字典并使用json.dump写入文件:

df = pd.DataFrame([{"invoiceDate":"18/08/2019","amount":1140.87}])
print (df)
  invoiceDate   amount
0  18/08/2019  1140.87


import json
with open('data.json', 'w') as f:
    json.dump(df.to_dict(orient='records'), f)

#[{"invoiceDate": "18/08/2019", "amount": 1140.87}]

I used the replace function in the data-frame to replace forward slash as per my need.我根据需要在data-frame使用了替换功能来替换正斜杠。

The following code helped me to archive my desire output.以下代码帮助我归档了我的愿望输出。

df1 = df.to_json(orient='records',lines=True).replace('\\r\\n', " ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM