You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中通过JSON将CSV数字解析为int或float类型

解决CSV转JSON时数字字段类型转换问题

问题的核心在于csv.DictReader会默认把CSV里的所有值都读取为字符串类型——哪怕你写入CSV时已经做过类型转换也没用,因为CSV本身是纯文本格式,不保留任何类型信息。要得到你期望的int类型,需要在读取每行数据后手动转换对应字段的类型。

修改后的代码

import json
import csv

csvfile_ind = open("test.csv", 'r')
reader_ind = csv.DictReader(csvfile_ind)
json_file_ind = open("test_json.json", 'w')

for row in reader_ind:
    # 转换RRC_attempts为int类型
    row['RRC_attempts'] = int(row['RRC_attempts'])
    # 先转float再转int,处理100.0这类小数格式的字符串
    row['rrc_succ_rate'] = int(float(row['rrc_succ_rate']))
    # 写入JSON时添加换行,让每个对象单独成行,提升可读性
    json_file_ind.write(json.dumps(row, sort_keys=False, indent=4, separators=(',', ': ')) + '\n')

关键细节说明

  1. RRC_attempts的转换:直接用int()转换即可,因为CSV里这个字段的值都是整数格式的字符串(比如"1"、"0"),没有小数干扰。
  2. rrc_succ_rate的转换:先转float()再转int()是为了兼容100.0这种带小数的字符串——直接用int()转换"100.0"会报错,先转成浮点数再取整就能得到你要的100整数类型。
  3. 换行符的添加:原代码里多次写入JSON对象会挤在一起,加上+ '\n'可以让每个JSON对象单独占一行,后续查看或解析更方便。

如果后续有更多需要转换类型的字段,可以把转换逻辑封装成函数,让代码更易维护:

def convert_field_types(row):
    # 定义字段对应的转换规则
    type_converters = {
        'RRC_attempts': int,
        'rrc_succ_rate': lambda x: int(float(x))
    }
    for field, converter in type_converters.items():
        if field in row:
            row[field] = converter(row[field])
    return row

# 循环中调用转换函数
for row in reader_ind:
    processed_row = convert_field_types(row)
    json_file_ind.write(json.dumps(processed_row, sort_keys=False, indent=4, separators=(',', ': ')) + '\n')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:11:31