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

使用Pandas读取CSV时因空列导致全表NA问题的解决方法

解决Pandas读取含空列CSV时全表NA的问题

遇到这种因空列导致Pandas无法正确解析CSV的情况,核心思路是先手动预处理文件,过滤掉那两个空列,再用Pandas加载——既然直接用read_csv的参数(比如usecols)无效,我们可以绕开Pandas的自动解析,手动掌控列的筛选逻辑:

方法一:用Python内置csv模块预处理后转DataFrame

这个方法最可靠,完全规避Pandas解析空列时的异常:

import pandas as pd
import csv

# 替换成你的文件路径
file_path = "your_export.csv"

# 第一步:读取并筛选列
with open(file_path, 'r', encoding='cp1252') as f:
    # 按指定分隔符读取文件
    reader = csv.reader(f, delimiter=';')
    # 获取原始表头
    header = next(reader)
    # 定义要排除的空列名
    exclude_cols = ['Recipient 1', 'Recipient 2']
    # 计算需要保留的列索引
    keep_idx = [i for i, col_name in enumerate(header) if col_name not in exclude_cols]
    # 生成新表头
    new_header = [header[i] for i in keep_idx]
    # 处理所有数据行:只保留指定索引的内容
    data_rows = []
    for row in reader:
        cleaned_row = [row[i] for i in keep_idx]
        data_rows.append(cleaned_row)

# 第二步:转换为DataFrame并处理数值列
df = pd.DataFrame(data_rows, columns=new_header)
# 将Amount列转为数值类型(手动读取的是字符串,需替换小数点分隔符)
df['Amount'] = pd.to_numeric(df['Amount'].str.replace(',', '.'))

方法二:尝试切换解析引擎

如果不想手动处理,也可以试试切换到Python引擎(默认是C引擎,对某些不规则CSV兼容性稍差),可能能正确识别列结构,之后再删除空列:

import pandas as pd

df = pd.read_csv(
    "your_export.csv",
    sep=';',
    decimal=',',
    encoding='cp1252',
    engine='python'
)
# 删除不需要的空列
df = df.drop(columns=['Recipient 1', 'Recipient 2'])

为什么之前的方法无效?

  • usecols无效:因为Pandas无法正确解析原始CSV的列名(返回Unnamed列),指定原列名自然匹配不到。
  • header=None, skiprows=1全NA:空列导致Pandas的分隔符解析逻辑出错,连数据行的结构都识别不了,因此全表显示NA。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:35:13