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

使用Python+Google Sheets API读取逗号分隔小数数值的问题求助

解决方案

问题根因:gspread默认读取数值时会将逗号识别为千分位分隔符,自动过滤后转换为整数,所以会出现0,8读取为8的情况。无需修改原表格格式,可通过以下两种方案解决:

方案1:读取原始字符串后自行转换(最稳定)

不要使用get_all_records()的自动数值转换逻辑,改用get_all_values()读取所有单元格的原始展示内容,再自行处理格式:

sheet = google_sheets_connection() # API连接
sheet = sheet.worksheet(sheet_name)
# 读取原始字符串格式的所有单元格内容,第一行默认是表头
raw_data = sheet.get_all_values()
headers = raw_data[0]
processed_data = []
for row in raw_data[1:]:
    processed_row = {}
    for idx, val in enumerate(row):
        # 对需要转换的小数字段处理,也可以全量处理
        if ',' in val and val.replace(',', '').isdigit():
            processed_row[headers[idx]] = float(val.replace(',', '.'))
        else:
            processed_row[headers[idx]] = val
    processed_data.append(processed_row)
print(processed_data)

方案2:修改get_all_records参数获取格式化值

调用get_all_records()时指定value_render_option参数为FORMATTED_VALUE,强制返回单元格展示的字符串格式,再做替换处理:

sheet = google_sheets_connection() # API连接
sheet = sheet.worksheet(sheet_name)
# 指定返回格式化后的字符串,不自动转数值
raw_records = sheet.get_all_records(value_render_option='FORMATTED_VALUE')
processed_data = []
for record in raw_records:
    processed_record = {}
    for k, v in record.items():
        if isinstance(v, str) and ',' in v and v.replace(',', '').isdigit():
            processed_record[k] = float(v.replace(',', '.'))
        else:
            processed_record[k] = v
    processed_data.append(processed_record)
print(processed_data)

如果你的表格中存在负的逗号分隔小数(例如-0,8),可以将判断条件调整为v.lstrip('-').replace(',', '').isdigit()即可兼容。如果明确知道哪些字段是逗号分隔的小数,也可以直接针对指定字段做替换转换,不需要全量判断,效率和准确率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:00:01