Python 列数据类型,带pandas read_json
我有一个json文件,如下所示:Python 列数据类型,带pandas read_json,python,pandas,Python,Pandas,我有一个json文件,如下所示: [{"A": 0, "B": "x"}, {"A": 1, "B": "y", "C": 0}, {"A": 2, "B": "z", "C": 1}] 由于“C”列包含NaN值(第一行),pandas会自动推断其数据类型为“float64”: 但是,我希望“C”列的数据类型为“Int32”pd.read_json(路径,dtype={“C”:“Int32”})不起作用: >>> pd.read_json(path, dtype={"C":
[{"A": 0, "B": "x"}, {"A": 1, "B": "y", "C": 0}, {"A": 2, "B": "z", "C": 1}]
由于“C”列包含NaN值(第一行),pandas会自动推断其数据类型为“float64”:
但是,我希望“C”列的数据类型为“Int32”pd.read_json(路径,dtype={“C”:“Int32”})
不起作用:
>>> pd.read_json(path, dtype={"C": "Int32"}).C.dtype
dtype('float64')
相反,pd.read_json(path).astype({“C”:“Int32”})
可以工作:
>>> pd.read_json(path).astype({"C": "Int32"}).C.dtype
Int32Dtype()
为什么会发生这种情况?如何仅使用pd.read\u json
函数设置正确的数据类型?原因如下:
它将'Int32'
转换为numpy.Int32
,然后在尝试将整个列(数组)转换为此类型时,会导致值错误(无法将非有限值(NA或inf)转换为整数)。因此,原始(未转换)数据将在异常块中返回。我猜这是熊猫身上的某种虫子,至少这种行为没有正确的记录 另一方面,
astype
的工作原理不同:它在系列中是元素级的,因此可以创建混合类型列
有趣的是,当直接指定pd.Int32Dtype()
时(而不是它的字符串别名'Int32'
),您第一眼就能得到所需的结果,但如果您查看类型,它们仍然是浮动的:
df = pd.read_json(json, dtype={"C": pd.Int32Dtype})
print(df)
# A B C
#0 0 x NaN
#1 1 y 0
#2 2 z 1
print(df.C.map(type))
#0 <class 'float'>
#1 <class 'float'>
#2 <class 'float'>
#Name: C, dtype: object
df=pd.read_json(json,dtype={“C”:pd.Int32Dtype})
打印(df)
#A、B、C
#0xNaN
#1 y 0
#2 2 z 1
打印(df.C.map(类型))
#0
#1
#2
#名称:C,数据类型:object
作为比较:
print(df.C.astype('Int32').map(type))
#0 <class 'pandas._libs.missing.NAType'>
#1 <class 'int'>
#2 <class 'int'>
#Name: C, dtype: object
打印(df.C.astype('Int32').map(type))
#0
#1
#2
#名称:C,数据类型:object
谢谢您的回答。我将等待其他答案,如果没有其他人来,我将标记您的答案为已接受!:)
df = pd.read_json(json, dtype={"C": pd.Int32Dtype})
print(df)
# A B C
#0 0 x NaN
#1 1 y 0
#2 2 z 1
print(df.C.map(type))
#0 <class 'float'>
#1 <class 'float'>
#2 <class 'float'>
#Name: C, dtype: object
print(df.C.astype('Int32').map(type))
#0 <class 'pandas._libs.missing.NAType'>
#1 <class 'int'>
#2 <class 'int'>
#Name: C, dtype: object