如何使用Python Pandas从CSV文件中提取2018年6月和9月的s_001字段值
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

