You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用.loc便捷选取DataFrame的连续与非连续列?

Cleaner Ways to Select Mixed Column Ranges and Individual Columns with .loc

Great question—when you're working with large DataFrames, writing concise column selection code saves a lot of time. Your current approach works, but there are more streamlined methods to avoid building the column list step-by-step.

Here are a few handy alternatives:

1. Unpack the Column Slice Directly in the List

You can use the unpacking operator (*) to convert the column slice into individual elements, then add your standalone column(s) right in the list passed to .loc:

import pandas as pd

df = pd.DataFrame({'a': [1], 'b': [1], 'c': [1], 'd':[1], 'e':[1]})
df.loc[:, [*df.columns['a':'c'], 'e']]

This is super readable and lets you do the selection in one line—no need to create an intermediate list variable.

2. Use pd.Index.union() for Safe Combination

If you want to ensure no duplicate columns (useful in more complex scenarios), you can combine the slice and standalone columns using union():

cols = df.columns['a':'c'].union(['e'])
df.loc[:, cols]

This method automatically removes any duplicate column names, which is a nice safeguard if your standalone columns might overlap with the range.

3. Combine with np.r_ (Using Column Positions)

If you prefer working with column positions instead of names, you can use numpy.r_ to concatenate the position ranges, then use .iloc (a useful alternative even though you asked for .loc):

import numpy as np

col_positions = np.r_[df.columns.get_loc('a'):df.columns.get_loc('c')+1, df.columns.get_loc('e')]
df.iloc[:, col_positions]

Why Your Original Idea ['a':'c', 'e'] Doesn't Work

Just to clarify: Python lists don't support slicing syntax inside them (like ['a':'c']), which is why that approach throws an error. The methods above work by converting the column slice into a proper iterable of column names first, then combining it with your standalone columns.

内容的提问来源于stack exchange,提问作者Edward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:10:58