求助:日期格式无法处理及'int'对象无'toordinal'属性报错
Hey there, let's break down and solve your two problems one by one:
1. Why you're seeing "Date format can't be handled as date"
Your df1['Date'] series contains float values, which pandas/matplotlib can't natively interpret as dates. Floats (like 20230101.0) aren't recognized as valid date inputs, hence the format error.
2. Why the AttributeError: 'int' object has no attribute 'toordinal' happens
When you try to plot with float dates, matplotlib implicitly converts them to integers (to drop the decimal) and then tries to treat those integers as date objects. But plain integers don't have the toordinal() method that matplotlib uses to handle date plotting—this is exactly what triggers the error.
Step-by-Step Solutions
First: Convert the Date column to a proper datetime type
You'll need to convert those float values into pandas datetime objects. The exact code depends on your date's underlying format, but here's the most common scenario (assuming your floats represent dates like YYYYMMDD, e.g., 20230101.0):
import pandas as pd # Convert float -> int (to remove .0) -> string -> datetime df1['Date'] = pd.to_datetime(df1['Date'].astype(int).astype(str), format='%Y%m%d')
- If your date format is different: Adjust the
formatparameter. For example, if your floats are2023.01.01, you'd first replace the dots with hyphens:df1['Date'] = pd.to_datetime( df1['Date'].astype(str).str.replace('.', '-'), format='%Y-%m-%d' ) - Handle missing values: If there are
NaNs in your Date column, adderrors='coerce'to convert invalid entries toNaT(Not a Time):df1['Date'] = pd.to_datetime(df1['Date'].astype(int).astype(str), format='%Y%m%d', errors='coerce')
Second: Update your plotting code
Once your Date column is in datetime format, matplotlib will handle it correctly without the toordinal error. Here's your full corrected code (I also added an initial value for performance since it looks like you're starting from index 2265):
import pandas as pd import matplotlib.pyplot as plt # Fix the Date column first df1['Date'] = pd.to_datetime(df1['Date'].astype(int).astype(str), format='%Y%m%d') # Initialize performance array with matching length to df1 performance = [0.0] * df1.shape[0] performance[2265] = 1.0 # Set your starting performance value here # Calculate performance for i in range(2266, df1.shape[0]): performance[i] = performance[i-1] * (1 + r[i]) df1['performance'] = performance print(performance[2267]) # Plot without date errors plt.plot(df1['Date'][2265:4616], df1['performance'][2265:4616]) plt.xlabel('Date') plt.ylabel('Performance') plt.xticks(rotation=45) # Optional: Rotate dates for readability plt.show()
内容的提问来源于stack exchange,提问作者Rawia Sammout

