IndexError: positional indexers are out-of-bounds在已刪除行但不在全新DataFrame 上的 DataFrame 上運行以下代碼時出現錯誤:我正在使用以下方法來清理數據:import pandas as pddef get_list_of_corresponding_projects(row: pd.Series, df: pd.DataFrame) -> list: """Returns a list of indexes indicating the 'other' (not the current one) records that are for the same year, topic and being a project. """ current_index = row.name current_year = row['year'] current_topic = row['topic'] if row['Teaching Type'] == "Class": mask = (df.index != current_index) & (df['year'] == current_year) & (df['topic'] == current_topic) & (df['Teaching Type'] == "Project") return df[mask].index.values.tolist() else: return list()def fix_classes_with_corresponding_projects(df: pd.DataFrame) -> pd.DataFrame: """Change the Teaching Type of projects having a corresponding class from 'Project' to 'Practical Work' """ # find the projects corresponding to that class df['matching_lines'] = df.apply(lambda row: get_list_of_corresponding_projects(row, df), axis=1) # Turn the series of lists into a single list without duplicates indexes_to_fix = list(set(sum(df['matching_lines'].values.tolist(), []))) # Update the records df.iloc[indexes_to_fix, df.columns.get_loc('Teaching Type')] = "Practical Work" # Remove the column that was used for tagging df.drop(['matching_lines'], axis=1, inplace=True) # return the data return df在全新的DataFrame上運行時,這些方法可以正常工作:df = pd.DataFrame({'year': ['2015','2015','2015','2016','2016','2017','2017','2017','2017'], 'Teaching Type':['Class', 'Project', 'Class', 'Class', 'Project', 'Class', 'Class', 'Class', 'Project' ], 'topic': ['a', 'a', 'b', 'a', 'c','a','b','a','a']})display(df)df = fix_classes_with_corresponding_projects(df)display(df)上面的示例在以下行中受到影響:df.iloc[indexes_to_fix, df.columns.get_loc('Teaching Type')] = "Practical Work"我在這里想念什么?我認為,當我使用索引值時,我可以避免這種類型的錯誤。
1 回答

元芳怎么了
TA貢獻1798條經驗 獲得超7個贊
您的fix_classes_with_corresponding_projects
函數存在邏輯缺陷:indexes_to_fix
包含要修復的行的索引值(而不是索引位置)。然后使用 選擇iloc
,它按位置選擇行。你需要的是
# Update the records df.loc[indexes_to_fix, 'Teaching Type'] = "Practical Work"
代替
df.iloc[indexes_to_fix, df.columns.get_loc('Teaching Type')] = "Practical Work"
所以你的原始代碼只是巧合。如果您有一個非數字索引(例如,使用創建示例數據框index=list('abcdefghi')
),該缺陷將立即變得明顯。
添加回答
舉報
0/150
提交
取消