我知道去掉一列要用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')。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象