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

如何用Pandas read_csv按指定时间段筛选CSV文件行?

Fixing NaN Values When Filtering CSV by Date Range

The issue you're facing comes down to two key problems in your code:

  1. You're trying to index the Price series using dates that aren't set as the DataFrame's index.
  2. There's a case mismatch between your CSV column name (Price) and how you're accessing it (abc1.price looks for a lowercase price column).

Here are two straightforward solutions to resolve this:

Solution 1: Set Date as the Index When Reading the CSV

By making the Date column your DataFrame's index, you can easily slice the data using date ranges:

import pandas as pd
from datetime import datetime

filesource1 = "your_file.csv"
# Read CSV, parse dates, and set Date as the index
abc1 = pd.read_csv(filesource1, parse_dates=['Date'], index_col='Date')
# Access the Price column correctly (matches CSV column name)
abc2 = abc1['Price']

startDate = datetime(2014, 8, 1)
endDate = datetime(2018, 3, 1)

# Slice the series using the date range
abc3 = abc2.loc[startDate:endDate]
print(abc3.head())

Solution 2: Use Boolean Filtering (No Index Change Needed)

If you prefer to keep the default integer index, you can filter rows using boolean conditions on the Date column:

import pandas as pd
from datetime import datetime

filesource1 = "your_file.csv"
abc1 = pd.read_csv(filesource1, parse_dates=['Date'])

startDate = datetime(2014, 8, 1)
endDate = datetime(2018, 3, 1)

# Filter rows where Date is within your desired range
filtered_rows = abc1[(abc1['Date'] >= startDate) & (abc1['Date'] <= endDate)]
# Extract the Price column from the filtered data
abc3 = filtered_rows['Price']
print(abc3.head())

Key Notes:

  • Always use bracket notation (abc1['Price']) instead of dot notation (abc1.price) to access columns, especially if the column name has uppercase letters or spaces. This avoids case-sensitivity issues.
  • The parse_dates=['Date'] argument ensures pandas recognizes the Date column as datetime objects, which is essential for date-based filtering.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:29:26