簡體   English   中英

有沒有辦法防止 Pandas read_json (orient='split') 機會主義地將 float64 列轉換為 int64?

[英]Is there a way to prevent Pandas read_json (orient='split') from opportunistically converting a float64 column to int64?

我希望能夠在 pandas 中使用 read_json 來讀取一個 json 文件,該文件解釋列的方式與使用 to_json 編寫的方式相同。 在下面的示例中,當使用 to_json 寫入時,“Dec”列是 dtype float64,而 json 文件將數字顯示為浮點數(1.0、2.0 等)。 但是,當使用 read_json 讀取時,數據框中“Dec”的列類型最終為 int64。 我希望它仍然是 float64,即使值恰好都是整數。 如果這很重要,這些正在使用 orient='split' 。 有沒有辦法做到這一點? 我正在尋找一種通用方法,而不依賴於特定的列名,因為實際上我希望這可以在許多不同的數據幀上工作。

tmp_file = 'c:/Temp/in_df.json'
in_df = pd.DataFrame([['A', 2.0, 4], ['B', 3.0, 2], ['C', 4.0, 3]], columns=['Key', 'Dec', 'Num'])
dec_column_type_in = in_df['Dec'].dtype # float64
in_json = in_df.to_json(path_or_buf=tmp_file, orient='split', index=False)
out_df = pd.read_json(tmp_file, orient='split')
dec_column_type_out = out_df['Dec'].dtype # int64

您可以嘗試手動關閉 dtypes inferring

out_df = pd.read_json(tmp_file, orient='split', dtype=False)
print(out_df.dtypes)

Key     object
Dec    float64
Num      int64
dtype: object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM