【问题标题】:Select two sets of columns by column names in Pandas在 Pandas 中按列名选择两组列
【发布时间】:2018-06-29 13:51:13
【问题描述】:

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 syntax

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

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

也读过Selecting/Excluding sets of columns in Pandas

【问题讨论】:

  • 您能解释一下为什么stackoverflow.com/questions/14940743/… 不适合您吗?它似乎可以解决您的问题。
  • @cᴏʟᴅsᴘᴇᴇᴅ,抱歉,我不知道它对我有什么用。该线程的接受答案给出了df.drop(columns = ['food', 'height'])之类的答案,就像我在帖子中提到的那样。此外,那里的所有答案似乎都需要显式输入所有列名。但是我在帖子中已经清楚地写道,我想删除的列名太多了,无法输入。

标签: python pandas dataframe


【解决方案1】:

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

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

【讨论】:

  • @jezrael 也许......这次我没看。如果是,我会删除,没有问题
  • 关于 OP 的最后一个链接。
  • 谢谢,但我确实需要一个更通用的解决方案,并且不需要 需要显式键入所有列名。此外,~让我更加困惑。是像not! 这样的东西吗?为什么 Python 在 "not" 表达式中如此不一致?
  • @ytu 另外, ~ 是您对数据框和系列执行否定的方式。它是按位 NOT 运算符的重载版本,但在语义上还有其他含义。
  • @cᴏʟᴅsᴘᴇᴇᴅ 非常感谢您的帮助。现在df[df.columns.difference(c)]df[np.setdiff1d(df.columns, c)] 为我工作,但df[~df.columns.isin(c)] 给了我ValueError: Item wrong length 6 instead of 7. 你介意检查一下吗?
【解决方案2】:

首先通过Index.get_loc获取列名的位置,然后使用numpy.r_将所有切片器连接在一起:

a = np.r_[df.columns.get_loc('age'):df.columns.get_loc('color')+1, 
          df.columns.get_loc('score'):df.columns.get_loc('state')+1]

df = df.iloc[:, a]
print (df)
           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

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 2017-08-30
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2023-04-05
    • 2017-01-29
    相关资源
    最近更新 更多