Pandas to_json 更改数据类型

问题描述 投票:0回答:2

我注意到了这种行为,但不确定这是一个错误。 我创建了一个包含 2 个整数列和 1 个浮点列的数据框

import pandas as pd
df = pd.DataFrame([[1,2,0.2],[3,2,0.1]])
df.info()


<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 3 columns):
0    2 non-null int64
1    2 non-null int64
2    2 non-null float64
dtypes: float64(1), int64(2)

如果我将其输出为 Json,则 dtype 信息会丢失:

df.to_json(orient= 'records')

'[{"0":1.0,"1":2.0,"2":0.2},{"0":3.0,"1":2.0,"2":0.1}]'

所有数据均转换为浮点型。如果例如一列包含 ns 时间戳,这就是一个问题,因为它们会转换为指数表示法并且亚秒信息会丢失。

我也在这里提交了问题:https://github.com/pydata/pandas/issues/7583

我期待的结果是:

'[{"0":1,"1":2,"2":0.2},{"0":3,"1":2,"2":0.1}]'
python json pandas
2个回答
2
投票

一种方法是使用对象 dtype 查看 DataFrame 列:

In [11]: df1 = df.astype(object)

In [12]: df1.to_json()
Out[12]: '{"0":{"0":1,"1":3},"1":{"0":2,"1":2},"2":{"0":0.2,"1":0.1}}'

In [13]: df1.to_json(orient='records')
Out[13]: '[{"0":1,"1":2,"2":0.2},{"0":3,"1":2,"2":0.1}]'

0
投票

是的,我注意到相同的行为,如果列中的所有值看起来都像类型,它只会自动检测并转换它。 在 m 的情况下,我必须稍后在另一个模块中将其转换回数据帧,这是一场噩梦,所以我必须存储数据类型信息以保持数据完整性(我发现这比使用其他 json 格式要好得多)就像“记录”应该“分割”或“索引”一样,就像这样:

# Before converting to JSON , store the datatypes using 
data_types = data.dtypes
#I stored it in my redis server

#then after converting back :
def ensure_data_type_integrity(data, data_types):
 `enter code here`for column, dtype in data_types.iteritems():
     if dtype == 'object':
         try:
             data[column] = data[column].astype(dtype)
         except ValueError:
             print(f"Conversion error: Unable to convert column '{column}' to '{dtype}'")
© www.soinside.com 2019 - 2024. All rights reserved.