You need to enable JavaScript to run this app. pandas使用json_normalize加载JSON时如何自动将符合条件的数值转整数
优惠活动
大模型
产品
解决方案
定价
更多

pandas使用json_normalize加载JSON时如何自动将符合条件的数值转整数

自动转换pandas中含缺失值的潜在整数列方案

你可以通过逐列判断的方式实现自动转换,核心逻辑是仅对数值类型的列做校验,如果该列所有非空值都是整数,就转换为pandas支持空值的整数类型,其余列保持原样。

核心实现代码

import pandas as pd
import numpy as np

def auto_convert_int_columns(df):
    for col in df.columns:
        # 跳过非数值类型列
        if not pd.api.types.is_numeric_dtype(df[col]):
            continue
        # 单独跳过布尔类型,避免被误判为整数
        if pd.api.types.is_bool_dtype(df[col]):
            continue
        # 提取非空值校验是否全部为整数
        non_na_vals = df[col].dropna()
        if (non_na_vals % 1 == 0).all():
            # 转换为支持空值的整数类型,首字母I大写
            df[col] = df[col].astype('Int64')
    return df

测试效果示例

用你提供的测试用例运行:

df = pd.DataFrame({
    'Strings': ['abc', 'def', 'ghi'],
    'Integers': [1, None, 3],
    'Floats': [13.55, 151.1586, 21.0053]
})

# 转换前Integers列类型为float64,取值为1.0、NaN、3.0
print("转换前列类型:\n", df.dtypes)

df = auto_convert_int_columns(df)

# 转换后Integers列类型为Int64,取值为1、<NA>、3
print("\n转换后列类型:\n", df.dtypes)
print("\n转换后Integers列取值:\n", df['Integers'])

运行后字符串列、浮点列的类型和取值完全不变,仅潜在整数列完成类型转换。

注意事项

  • 该方案依赖pandas 1.0及以上版本提供的可空整数类型Int64,原生支持缺失值存储,不会触发普通int类型遇到空值强制转float的问题
  • 逻辑默认跳过布尔类型、非数值类型,不会修改字符串、布尔值、真实浮点列的原有状态
  • 如果业务中存在需要保留为float格式的全整数浮点列,可以在判断逻辑中增加自定义过滤规则,比如按列名规则排除即可

内容的提问来源于stack exchange,提问作者mrgou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 07:36:02