我知道去掉一列要用df。Drop ('column name', axis=1)。是否有一种方法可以使用数字索引而不是列名来删除列?


当前回答

如果有多个具有相同名称的列,那么到目前为止给出的解决方案将删除所有列,这可能不是我们要寻找的。如果试图删除除一个实例之外的重复列,则可能会出现这种情况。下面的例子说明了这种情况:

# make a df with duplicate columns 'x'
df = pd.DataFrame({'x': range(5) , 'x':range(5), 'y':range(6, 11)}, columns = ['x', 'x', 'y']) 


df
Out[495]: 
   x  x   y
0  0  0   6
1  1  1   7
2  2  2   8
3  3  3   9
4  4  4  10

# attempting to drop the first column according to the solution offered so far     
df.drop(df.columns[0], axis = 1) 
   y
0  6
1  7
2  8
3  9
4  10

可以看到,两个x列都被删除了。 可选择的解决方案:

column_numbers = [x for x in range(df.shape[1])]  # list of columns' integer indices

column_numbers .remove(0) #removing column integer index 0
df.iloc[:, column_numbers] #return all columns except the 0th column

   x  y
0  0  6
1  1  7
2  2  8
3  3  9
4  4  10

如您所见,这实际上只删除了第0列(第一个'x')。

其他回答

您可以使用下面的行删除前两列(或任何您不需要的列):

df.drop([df.columns[0], df.columns[1]], axis=1)

参考

像这样删除多个列:

cols = [1,2,4,5,12]
df.drop(df.columns[cols],axis=1,inplace=True)

inplace=True用于在数据帧本身中进行更改,而不需要在数据帧的副本上进行列删除。如需保留原稿,请使用:

df_after_dropping = df.drop(df.columns[cols],axis=1)

由于可以有多个具有相同名称的列,我们应该首先重命名列。 下面是解决方案的代码。

df.columns=list(range(0,len(df.columns)))
df.drop(columns=[1,2])#drop second and third columns

获得你想要的列的好方法(没有问题重复的名称)。

例如,您希望删除的列索引包含在类似列表的变量中

unnecessary_cols = [1, 4, 5, 6]

then

import numpy as np
df.iloc[:, np.setdiff1d(np.arange(len(df.columns)), unnecessary_cols)]

如果有多个具有相同名称的列,那么到目前为止给出的解决方案将删除所有列,这可能不是我们要寻找的。如果试图删除除一个实例之外的重复列,则可能会出现这种情况。下面的例子说明了这种情况:

# make a df with duplicate columns 'x'
df = pd.DataFrame({'x': range(5) , 'x':range(5), 'y':range(6, 11)}, columns = ['x', 'x', 'y']) 


df
Out[495]: 
   x  x   y
0  0  0   6
1  1  1   7
2  2  2   8
3  3  3   9
4  4  4  10

# attempting to drop the first column according to the solution offered so far     
df.drop(df.columns[0], axis = 1) 
   y
0  6
1  7
2  8
3  9
4  10

可以看到,两个x列都被删除了。 可选择的解决方案:

column_numbers = [x for x in range(df.shape[1])]  # list of columns' integer indices

column_numbers .remove(0) #removing column integer index 0
df.iloc[:, column_numbers] #return all columns except the 0th column

   x  y
0  0  6
1  1  7
2  2  8
3  3  9
4  4  10

如您所见,这实际上只删除了第0列(第一个'x')。