在数据框中删除行时索引超出边界



我不明白为什么我得到错误&;IndexError: index 159超出了轴0的边界,尺寸为159&;当从数据框中删除行列表时。

#Import file Excel
xls = pd.ExcelFile(file_path)
#Parse away the first 5 rows
df = xls.parse('Daten', skiprows=5, index_col=None, na_values=['NA'])
# Select row where value in column "Punktrolle_SO" is not 'UK_Schwelle_Wehr_Blockrampe'   
row_numbers = [x+1 for x in df[df['Punktrolle_SO'] != 'UK_Schwelle_Wehr_Blockrampe'].index]
#Changing the index to skip the index 0
df.index = df.index + 1
#Dropping the rows where the data are not 'UK_Schwelle_Wehr_Blockrampe'
dataframe = df.drop(df.index[row_numbers], inplace=True)

列表row_numbers包含正确的156值和数据帧索引从1到159,所以为什么我得到一个IndexError?

runfile('O:/GIS/GEP/Risikomanagement/Flussvermessung/ALD/Analyses/ReadMultileFilesInOne.py', wdir='O:/GIS/GEP/Risikomanagement/Flussvermessung/ALD/Analyses')
Traceback (most recent call last):
File "O:GISGEPRisikomanagementFlussvermessungALDAnalysesReadMultileFilesInOne.py", line 73, in <module>
dataframe = df.drop(df.index[row_numbers], inplace=True)
File "C:ProgramDataAnaconda3libsite-packagespandascoreindexesrange.py", line 708, in __getitem__
return super().__getitem__(key)
File "C:ProgramDataAnaconda3libsite-packagespandascoreindexesbase.py", line 3941, in __getitem__
result = getitem(key)
IndexError: index 159 is out of bounds for axis 0 with size 159

谁能帮我看看我做错了什么?谢谢你,

大卫。

我期望一个包含Excel文件行的数据框,其中列"Punktrolle_SO"= 'UK_Schwelle_Wehr_Blockrampe'.

保持包含UK_Schwelle_Wehr_Blockrampe使用的行不是更好吗?:

df[df["Punktrolle_SO"].str.contains("UK_Schwelle_Wehr_Blockrampe")]

如果数据框的大小为159,则最高索引为158。这是因为指标从0开始,而不是1。您正在尝试访问一个比最大值高1的索引。

数据帧不是从1到159,而是从0到158。因此索引159将越界。您需要将访问偏移1。

最新更新