如何用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:
- You're trying to index the Price series using dates that aren't set as the DataFrame's index.
- There's a case mismatch between your CSV column name (
Price) and how you're accessing it (abc1.pricelooks for a lowercasepricecolumn).
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
相关产品推荐
相关产品推荐

