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

如何解决Python读取CSV时出现的KeyError: 'Niveau'错误?

解决KeyError: 'Niveau'的问题

第一步:确认DataFrame的实际列名

先在读取CSV后添加一行代码,打印所有列名,排查是否存在列名不一致的情况:

import pandas as pd

file_path = r"C:\Users\Roman\OneDrive\Desktop\Finaltest.csv"
df = pd.read_csv(file_path)
# 打印所有列名,检查是否有空格、大小写差异或特殊字符
print(df.columns.tolist())

多数情况下问题出在这些细节:

  • 列名带有前后空格(比如' Niveau'或'Niveau ')
  • 大小写不一致(比如'NIVEAU'而非'Niveau')
  • CSV使用非逗号分隔符(比如分号),导致pandas未正确解析列

如果是分隔符问题,读取时指定sep参数:

df = pd.read_csv(file_path, sep=';')  # 适用于分号分隔的CSV

第二步:修正代码中的语法错误

你代码里的row1.get['Niveau']是错误写法——get是方法而非字典属性,必须用括号调用,还可以设置默认值避免直接报错:

def combine_questions(row1, row2):
    # 用get方法获取值,不存在时返回None
    niveau1 = row1.get('Niveau', None)
    datentyp1 = row1.get('Datentyp', None)
    niveau2 = row2.get('Niveau', None)
    datentyp2 = row2.get('Datentyp', None)
    
    condition1 = niveau1 == '5 pt Likert' and datentyp1 == 'integer'
    condition2 = niveau2 == 'Metrisch' and datentyp2 == 'integer'
    
    if condition1 and condition2:
        return 'Test_LiMe'
    else:
        return None

第三步:可选优化(提升运行效率)

你当前的双重循环遍历所有行组合,数据量大时效率极低,可改用pandas向量操作替代:

# 标记符合两类条件的行索引
likert_idx = df[(df['Niveau'] == '5 pt Likert') & (df['Datentyp'] == 'integer')].index
metrisch_idx = df[(df['Niveau'] == 'Metrisch') & (df['Datentyp'] == 'integer')].index

# 若两类行都存在,批量标记Result列
if not likert_idx.empty and not metrisch_idx.empty:
    df.loc[likert_idx.union(metrisch_idx), 'Result'] = 'Test_LiMe'

核心排查点总结

  • 核对CSV列名,排除空格、大小写或特殊字符干扰
  • 确认读取CSV时使用了正确的分隔符
  • 修正get方法的调用语法(用括号而非方括号)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:00:56