Skip to main content
 首页 » 编程设计

python之在 Pandas 中按列名选择两组列

2025年01月19日12mayingbao

取Loc vs. iloc vs. ix vs. at vs. iat?的答案中的DataFrame例如。

df = pd.DataFrame( 
{'age':[30, 2, 12, 4, 32, 33, 69], 
 'color':['blue', 'green', 'red', 'white', 'gray', 'black', 'red'], 
 'food':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'], 
 'height':[165, 70, 120, 80, 180, 172, 150], 
 'score':[4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2], 
 'state':['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']}, 
 index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia'] 
) 

现在我想要除“食物”和“高度”之外的所有列。

我认为像 df.loc[:,['age':'color', 'score':'state']] 这样的东西会起作用,但是 Python 返回 SyntaxError: invalid语法.

我知道有一种解决方法:df.drop(columns = ['food', 'height'])。但是,在我的现实生活中,我有数百个列要删除。键入所有列名非常低效。

我期待与 dplyr::select(df, -(food:height)) 或 dplyr::select(df, age:color, score:state)在R语言中。

还阅读了 Selecting/Excluding sets of columns in Pandas .

请您参考如下方法:

首先,找到位于 food 和 height(含)之间的所有列。

c = df.iloc[-1:0].loc[:, 'food':'height'].columns 

接下来,过滤difference/isin/setdiff1d -

df[df.columns.difference(c)] 

或者,

df.loc[:, ~df.columns.isin(c)] 

或者,

df[np.setdiff1d(df.columns, c)] 

           age  color  score state 
Jane        30   blue    4.6    NY 
Nick         2  green    8.3    TX 
Aaron       12    red    9.0    FL 
Penelope     4  white    3.3    AL 
Dean        32   gray    1.8    AK 
Christina   33  black    9.5    TX 
Cornelia    69    red    2.2    TX