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

如何使用Python Pandas从CSV文件中提取2018年6月和9月的s_001字段值

Extract Specific Month Data from Date-Indexed DataFrame

Hey there! Let's break down how to grab the s_001 values for June and September 2018 from your DataFrame. Since you already have your data indexed by datetime, pandas makes this really straightforward—here are a couple of reliable methods:

Method 1: Direct Month-Based Slicing

Pandas datetime indexes understand partial date strings, so you can directly target the months you need with .loc:

# Get s_001 value for June 2018
june_s001 = df.loc['2018-06', 's_001']

# Get s_001 value for September 2018
september_s001 = df.loc['2018-09', 's_001']

print("June 2018 s_001:", june_s001)
print("September 2018 s_001:", september_s001)

Since your data only contains month-end entries, this will automatically pull the exact row for each month's last trading day.

Method 2: Use Your Pre-Generated Month-End Dates

You already created months_of_2018 with business month-end dates—you just need to use that index to slice into your DataFrame instead of only printing it. Here's how to adjust your code:

start_date = '2018-01-01'
end_date = '2018-12-31'
months_of_2018 = pd.date_range(start_date, end_date, freq='BM')

# Pull s_001 values for all 2018 month-ends first
all_month_end_data = df.loc[months_of_2018, 's_001']

# Filter to just June and September
june_sep_s001 = all_month_end_data[all_month_end_data.index.isin(['2018-06-29', '2018-09-28'])]

# Or skip the middle step and select those dates directly:
june_sep_s001 = df.loc[['2018-06-29', '2018-09-28'], 's_001']

print(june_sep_s001)

Quick Note on Your Original Code

The reason your initial code only printed dates is because months_of_2018 is just a standalone DatetimeIndex object—you need to pass it to your DataFrame's .loc accessor to retrieve the corresponding rows of data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 08:18:13