提问人:Dipesh Khadka 提问时间:11/15/2023 最后编辑:jpsDipesh Khadka 更新时间:11/15/2023 访问量:59
如何克服 python 中的 KeyError: 错误?[关闭]
How do i overcome the KeyError: error in python? [closed]
问:
我有一个CSV文件,我想用python分析它。我写了一个代码,问题似乎是KeyError:Niveau。在我的 CSV 文件中,有一列被命名为 Niveau。现在如何处理错误,让代码流动。代码是这样的:我尝试重命名 csv 文件中的列名,并且在代码中重命名列名,无论哪种方式都不起作用。我还尝试了 Row1.get['Niveau'] 函数,但效果不佳。错误如下所示:
import pandas as pd
# Read the CSV file into a DataFrame
file_path = r"C:\Users\Roman\OneDrive\Desktop\Finaltest.csv"
df = pd.read_csv(file_path)
# Function to combine questions based on conditions
def combine_questions(row1, row2):
condition1 = row1.get['Niveau'] == '5 pt Likert' and row1['Datentyp'] == 'integer'
condition2 = row2.get['Niveau'] == 'Metrisch' and row2['Datentyp'] == 'integer'
if condition1 and condition2:
return 'Test_LiMe'
else:
return None
# Create a new column 'Result' by combining questions
df['Result'] = None # Initialize the Result column
# Iterate through all combinations of questions and apply the combination function
for i in range(len(df)):
for j in range(i + 1, len(df)):
result = combine_questions(df.iloc[i], df.iloc[j])
if result:
df.at[i, 'Result'] = result
df.at[j, 'Result'] = result
# Print the DataFrame to verify the results
print(df)
runfile('C:/Users/Roman/Downloads/comm-master/comm-master/comm/ZTG_data.py')
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3629, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 136, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 163, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Niveau'
答:
0赞
Tadas
11/15/2023
#1
Python KeyError 异常是当您尝试访问不在字典 (dict) 中的密钥时引发的异常。
解决 方案:
- 使用 get 运算符,如果找不到值,它将返回 None,并且不会使您的代码崩溃。
row1.get("Niveau")
- 访问前检查。
if 'error' in response:
... # Parse the error state
else:
... # Parse the success state
- 使用 try-except。
ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
person = input('Get age for: ')
try:
print(f'{person} is {ages[person]} years old.')
except KeyError:
print(f"{person}'s age is unknown.")
评论