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

如何在Pandas中加载CSV并区分带/无引号值的数据类型

问题:Pandas加载CSV时混合数据类型识别异常

初始问题:DataFrame保存CSV后混合类型丢失

创建包含int和str混合类型的DataFrame,保存为CSV后重新加载,所有值被识别为int类型:

import pandas as pd

# 创建包含混合数据类型的DataFrame
data = {'columns': [1, 2, 3, '4', '5', '6']}
df = pd.DataFrame.from_dict(data)

# 保存前检查数据类型
selected_column = 'columns'
unique_types_before = {selected_column: set(df[selected_column].apply(type))}
print(unique_types_before)  # 输出: {'columns': {<class 'int'>, <class 'str'>}}

# 保存为CSV
df.to_csv('example.csv')

# 重新加载CSV
dataframe = pd.read_csv('example.csv')

# 加载后检查数据类型
unique_types_after = {selected_column: set(dataframe[selected_column].apply(type))}
print(unique_types_after)  # 输出: {'columns': {<class 'int'>}}

手动构造CSV后的需求与当前困境

手动创建manual_example.csv,内容如下:

columns
1
2
3
4
5
6
"7"

需求:加载该CSV时,带引号的值(如"7")识别为字符串,不带引号的值(如1)识别为数值。但现有代码将所有值识别为str类型:

import pandas as pd
from io import StringIO

csv_file_path = 'manual_example.csv'

with open(csv_file_path, 'r', encoding='utf-8') as file:
    csv_content = file.read()

csv_file = StringIO(csv_content)

# 读取CSV,指定列类型为object
df1 = pd.read_csv(csv_file, quotechar='"', dtype={'columns': object})
unique_types_df1 = {selected_column: set(df1[selected_column].apply(type))}
print(unique_types_df1)  # 输出: {'columns': {<class 'str'>}}

解决方案:自定义类型转换函数

利用pandas.read_csv的converters参数,自定义函数处理每个值的类型:

import pandas as pd

def convert_mixed_type(value):
    # 判断是否为带双引号的字符串
    if isinstance(value, str) and value.startswith('"') and value.endswith('"'):
        return value.strip('"')
    # 尝试转换为整数,失败则保留原字符串
    try:
        return int(value)
    except ValueError:
        return value

# 读取CSV时应用自定义转换器
df = pd.read_csv('manual_example.csv', converters={'columns': convert_mixed_type})

# 验证结果
unique_types = set(df['columns'].apply(type))
print(unique_types)  # 输出: {<class 'int'>, <class 'str'>}
print(df['columns'])

原理说明

  • converters参数会对指定列的每个值执行自定义转换逻辑
  • 先判断值是否被双引号包裹,若是则去除引号后保留为字符串
  • 未被引号包裹的值尝试转换为整数,无法转换的则保留原字符串格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 10:07:42