每个人

columns = ['a', 'c', 'e', 'f', 'g']
df2 = df.loc[:,~df.columns.isin(columns)]

我想知道是否有更像:

df2 = df.loc[:,'a': 'g']

但不包括"b"列.

第二种方法我做了两个命令,一个从a-g中 Select ,另一个从b中删除.

我想知道我是否可以从a-g中 Select ,同时删除b

推荐答案

The easiest way will be to use slice notation .loc as you demonstrated along with a call to .drop to remove any specific unwanted columns:

创建数据

>>> df = pd.DataFrame([[*range(10)]]*5, columns=[*'abcdefghij'])
>>> df
   a  b  c  d  e  f  g  h  i  j
0  0  1  2  3  4  5  6  7  8  9
1  0  1  2  3  4  5  6  7  8  9
2  0  1  2  3  4  5  6  7  8  9
3  0  1  2  3  4  5  6  7  8  9
4  0  1  2  3  4  5  6  7  8  9

.loc and dropping

相当简单,用.loc来执行切片,然后用drop来执行任何你不想要的东西.

>>> df.loc[:, 'a':'g'].drop(columns='b')
   a  c  d  e  f  g
0  0  2  3  4  5  6
1  0  2  3  4  5  6
2  0  2  3  4  5  6
3  0  2  3  4  5  6
4  0  2  3  4  5  6

使用索引

如果您希望尽可能高效地使用索引,可以使用Index.slice_indexer.drop,这样您就不会创建数据的临时子集(就像我们上面所做的那样):

>>> columns = df.columns[df.columns.slice_indexer('a', 'g')].drop('b')
>>> df[columns]
   a  c  d  e  f  g
0  0  2  3  4  5  6
1  0  2  3  4  5  6
2  0  2  3  4  5  6
3  0  2  3  4  5  6
4  0  2  3  4  5  6

Python相关问答推荐

try 与gemini-pro进行多轮聊天时出错

Pandas实际上如何对基于自定义的索引(integer和非integer)执行索引

max_of_three使用First_select、second_select、

如何根据参数推断对象的返回类型?

ModuleNotFound错误:没有名为flags.State的模块; flags不是包

Python中的嵌套Ruby哈希

将两只Pandas rame乘以指数

聚合具有重复元素的Python字典列表,并添加具有重复元素数量的新键

更改键盘按钮进入'

将9个3x3矩阵按特定顺序排列成9x9矩阵

创建可序列化数据模型的最佳方法

在Python中,从给定范围内的数组中提取索引组列表的更有效方法

Python逻辑操作作为Pandas中的条件

如何从需要点击/切换的网页中提取表格?

在matplotlib中删除子图之间的间隙_mosaic

剪切间隔以添加特定日期

交替字符串位置的正则表达式

将一个双框爆炸到另一个双框的范围内

将CSS链接到HTML文件的问题

PySpark:如何最有效地读取不同列位置的多个CSV文件