提问人:dipesh khadka 提问时间:11/18/2023 最后编辑:PM 77-1dipesh khadka 更新时间:11/18/2023 访问量:55
如何克服 Python 中的 KeyError:?
How can i overcome the KeyError: in Python?
问:
我想在python的帮助下分析CSV数据文件。但是发生错误,提示KeyError:Niveau。“Niveau”是我在 CSV 数据中的列的名称。
我有一个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'`
答: 暂无答案
评论