亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

IndexError:在刪除行的 DataFrame 上工作時,位置索引器超出范圍

IndexError:在刪除行的 DataFrame 上工作時,位置索引器超出范圍

慕姐8265434 2022-06-14 16:43:44
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')),該缺陷將立即變得明顯。


查看完整回答
反對 回復 2022-06-14
  • 1 回答
  • 0 關注
  • 426 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號