The issue with code is
在你的循环中,每次丢掉一列,你都会得到一组不同的列,因为你在每次迭代后都会把
df
覆盖回去。当你试图删除这组新列中的第3列时,你不仅删除了错误的一列,而且最终会耗尽所有的列。这就是为什么你会得到你所得到的错误。
iter1 -> 0,1,3,4,5,6,7,8,9,10 ... n #first you drop 2 which is 3rd col
iter2 -> 0,1,3,4,5,7,8,9,10 ... n #next you drop 6 which is 6th col (should be 5)
iter3 -> 0,1,3,4,5,7,8,9, ... n #next you drop 10 which is 9th col (should be 8)
你要做的是事先计算好索引,然后一次性删除它们。
你可以简单地只获得你想用范围删除的列的索引,然后放弃这些。
drop_idx = list(range(2,df.shape[1],3)) #Indexes to drop
df2 = df.drop(drop_idx, axis=1) #Drop them at once over axis=1
print('old columns->', list(df.columns))
print('idx to drop->', drop_idx)
print('new columns->',list(df2.columns))
old columns-> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
idx to drop-> [2, 5, 8]
new columns-> [0, 1, 3, 4, 6, 7, 9]
Note:这只是因为你的列名与索引相同。然而,如果你的列名不是这样的,你将不得不做一个额外的步骤,根据你想放弃的索引来获取列名。
drop_idx = list(range(2,df.shape[1],3))
drop_cols = [j for i,j in enumerate(df.columns) if i in drop_idx] #<--
df2 = df.drop(drop_cols, axis=1)