当列名为时间戳时,如何用字符串键选取DataFrame列?
I get it—transposing a large DataFrame just to pick columns by a partial timestamp string is a total waste of resources, and that error you're hitting is super frustrating. Let's skip the transpose workaround entirely and use these more efficient approaches tailored to timestamp column names:
1. Boolean Indexing with Native Datetime Attributes
Leverage the built-in datetime properties of your column index to create a precise, high-performance filter:
# Assuming your DataFrame's columns are a DatetimeIndex mask = (df.columns.year == 2000) & (df.columns.month == 5) selected_columns = df.loc[:, mask] print(selected_columns)
Why this works:
- DatetimeIndex columns have native
yearandmonthattributes, so we don’t need to convert values to strings. - This operates directly on the datetime metadata, making it one of the fastest options for large datasets.
2. Slice the Datetime Column Index
Use pandas' datetime slicing support directly on the column index with loc:
# Slice by exact date range for the month selected_columns = df.loc[:, '2000-05-01':'2000-05-31'] print(selected_columns)
Or for a cleaner month-level slice (no need to specify exact dates):
# Get slice positions for the entire month start_idx, end_idx = df.columns.slice_locs(start='2000-05', end='2000-05') selected_columns = df.iloc[:, start_idx:end_idx+1] print(selected_columns)
Why this works:
- Pandas recognizes datetime strings in slice operations for DatetimeIndex objects, even when they’re used as column names.
slice_locshandles the date range logic internally, so you don’t have to calculate start/end dates manually.
3. String-Based Partial Matching
If you prefer a more readable approach, convert column names to strings and use partial string matching:
selected_columns = df.loc[:, df.columns.astype(str).str.startswith('2000-05')] print(selected_columns)
Why this works:
- Converting Timestamps to strings lets you use pandas' string methods for intuitive partial matches.
- While this adds a tiny string conversion overhead, it’s still way more efficient than transposing a large DataFrame.
All these methods avoid the performance hit of transposing, and each fits different readability or precision needs—pick the one that works best for your use case!
内容的提问来源于stack exchange,提问作者Radoslaw Jurga

