使用df.at与df.loc获取标量值结果不一致问题咨询
df.at Throws Errors But df.loc Works in Pandas 0.20.3 Hey there, let's break down what's causing this issue and how to fix it quickly!
The Root Cause
You're working with pandas version 0.20.3, a relatively old release that has a known quirk with the at method when accessing datetime indexes using string dates.
Your DataFrame's index is made up of datetime objects (created via pd.date_range). While df.loc automatically converts your string '20130101' to a matching datetime index value, the at method in 0.20.3 doesn't handle this type conversion. It expects an exact datetime object match instead of a string, which is why you're seeing both TypeError and KeyError exceptions.
Fixes to Try
You have two reliable ways to resolve this:
1. Convert the string to a datetime object before using at
Explicitly parse your string date into a datetime that matches your index type. Here's the adjusted code:
import pandas as pd import numpy as np # Your original setup code dates = pd.date_range('20130101', periods=6) df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) # Convert string to datetime first target_date = pd.to_datetime('20130101') print(df.at[target_date, 'A']) # This will work as expected
2. Upgrade your pandas version
This compatibility issue was fixed in later pandas releases (starting around version 0.21.x). Upgrading to a newer, supported version lets you use df.at['20130101','A'] directly, just like you do with loc. To upgrade via pip:
pip install --upgrade pandas
Either approach will let you access the value you need without errors.
内容的提问来源于stack exchange,提问作者sagayev

