Python中生成CPI数据DataFrame遇月份递增问题求助
Hey there! Let's work through this together to get your CPI data into a DataFrame properly. The main issues with your current code are that you're not using the loop variable i to increment the month, and directly adding to the month number can lead to invalid dates (like month 13, which will throw an error). Here's how to fix it step by step:
First, let's fix the month increment problem
The datetime module's date object doesn't handle month increments natively (since months have varying days), so we have two solid options:
Option 1: Use dateutil.relativedelta (simpler)
This library lets you add months directly without worrying about year rollover. First, install it if you haven't:
pip install python-dateutil pandas
Then use this code to collect data and build your DataFrame:
import cpi from datetime import date from dateutil.relativedelta import relativedelta import pandas as pd # Set your starting date and number of months start_date = date(2022, 1, 1) # Adjust this to your desired start month n = 12 # Empty list to store our date-CPI pairs cpi_records = [] for i in range(n): # Add `i` months to the start date to get the current month current_date = start_date + relativedelta(months=i) # Fetch the CPI value for this date cpi_value = cpi.get(current_date) # Append the data as a dictionary (easy to convert to DataFrame later) cpi_records.append({"date": current_date, "cpi": cpi_value}) # Convert the list of dictionaries to a DataFrame cpi_df = pd.DataFrame(cpi_records) # Check the result print(cpi_df)
Option 2: Manual month/year calculation (no extra libraries)
If you don't want to install python-dateutil, you can calculate the year and month manually to handle rollover:
import cpi from datetime import date import pandas as pd start_year = 2022 start_month = 1 n = 12 cpi_records = [] for i in range(n): # Calculate current month and year total_months = start_month + i current_year = start_year + (total_months - 1) // 12 current_month = (total_months - 1) % 12 + 1 # Ensures month stays 1-12 current_date = date(current_year, current_month, 1) cpi_value = cpi.get(current_date) cpi_records.append({"date": current_date, "cpi": cpi_value}) cpi_df = pd.DataFrame(cpi_records)
Why your original code didn't work
- You were using
n+1(which is 13) as the month, which is invalid—date()will throw an error for months outside 1-12. - You weren't using the loop variable
ito increment the month, so every iteration tried to fetch the same invalid date.
Bonus: Handle missing data
Some months might not have CPI data available. To avoid crashes, add a try-except block:
for i in range(n): current_date = start_date + relativedelta(months=i) try: cpi_value = cpi.get(current_date) cpi_records.append({"date": current_date, "cpi": cpi_value}) except ValueError: print(f"Warning: No CPI data found for {current_date}")
内容的提问来源于stack exchange,提问作者corinthian74

