如何使用.loc便捷选取DataFrame的连续与非连续列?
.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

