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

当列名为时间戳时,如何用字符串键选取DataFrame列?

Efficiently Select Columns by Partial Timestamp String in Pandas

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 year and month attributes, 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_locs handles 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:24:47