求助:使用pandas读取Excel后,如何用loc访问日期类型列名的DataFrame列
Got it, let's work through this issue. The core problem here is that pandas automatically parses your Excel column header (which was a date string like 12/31/2018) into a Timestamp (datetime64) object when reading the file. That's why using a plain string or mismatched date type with loc isn't working. Here are three straightforward solutions:
1. Use the Exact Timestamp/Datetime Object to Access the Column
Since pandas converted the column name to a Timestamp, you can directly create a matching Timestamp or datetime object to target it:
import pandas as pd from datetime import datetime # Read your Excel file df = pd.read_excel("your_file.xlsx") # Option 1: Use pandas Timestamp target_column = pd.Timestamp("2018-12-31") # Option 2: Use datetime object (works too, since pandas converts it internally) target_column = datetime(2018, 12, 31) # Now access the column with loc column_data = df.loc[:, target_column]
Pro tip: Run print(df.columns) first to confirm the exact Timestamp format (it might show 2018-12-31 00:00:00, but the date alone is usually enough to match).
2. Prevent Pandas from Parsing Column Headers as Dates
If you'd rather keep the column names as plain strings (matching the original Excel format), you can read the file without letting pandas auto-parse the header dates. Here's how:
# Read the file without setting a header first df = pd.read_excel("your_file.xlsx", header=None) # Set the first row as column names, converting them to strings df.columns = df.iloc[0].astype(str) # Drop the now-redundant first row of data df = df.iloc[1:] # Now you can access the column using the original string name (e.g., '12/31/2018') column_data = df.loc[:, "12/31/2018"]
This method ensures your column names stay in their original Excel string format, no automatic datetime conversion.
3. Rename the Column to a Friendly String
If you want a more readable column name long-term, just rename it manually:
df = pd.read_excel("your_file.xlsx") # Rename the Timestamp column to your preferred string df.rename(columns={pd.Timestamp("2018-12-31"): "Dec_31_2018"}, inplace=True) # Now access it with the new name column_data = df.loc[:, "Dec_31_2018"]
Again, use print(df.columns) to double-check the exact Timestamp value you need to target in the rename dict.
内容的提问来源于stack exchange,提问作者Mohd Bilal

