gpt4 book ai didi

python - 带有 Pandas read_json 的列数据类型

转载 作者:行者123 更新时间:2023-12-04 09:47:58 28 4
gpt4 key购买 nike

我有一个看起来像这样的 json 文件:

[{"A": 0, "B": "x"}, {"A": 1, "B": "y", "C": 0}, {"A": 2, "B": "z", "C": 1}]

由于“C”列包含一个 NaN 值(第一行),pandas 会自动推断其 dtype 是“float64”:
>>> pd.read_json(path).C.dtype
dtype('float64')

但是,我希望“C”列的 dtype 为“Int32”。 pd.read_json(path, 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_json 设置正确的 dtype功能?

最佳答案

原因在this code section :

        dtype = (
self.dtype.get(name) if isinstance(self.dtype, dict) else self.dtype
)
if dtype is not None:
try:
dtype = np.dtype(dtype)
return data.astype(dtype), True
except (TypeError, ValueError):
return data, False

它转换 'Int32'numpy.int32当尝试将整个列(数组)转换为这种类型时,这会导致值错误(无法将非有限值(NA 或 inf)转换为整数)。因此,原始(未转换)数据在异常块中返回。
我猜这是 Pandas 中的某种错误,至少行为没有正确记录。
astype ,另一方面,工作方式不同:它 applies 'astype' 在系列上按元素排列),因此可以创建一个混合类型的列。

有趣的是,当指定 extension typepd.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

比较:
print(df.C.astype('Int32').map(type))
#0 <class 'pandas._libs.missing.NAType'>
#1 <class 'int'>
#2 <class 'int'>
#Name: C, dtype: object

关于python - 带有 Pandas read_json 的列数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62060809/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com