尝试访问命名索引时抛出 KeyError
KeyError thrown when trying to access named index
我正在尝试汇总一年中 2 个不同州的最低和最高温度。我的数据框中的列是日期、名称、Tmax、Tmin。
然而,当我尝试使用时:
df['Year'], df['Month-Date'] = zip(*df['Date'].apply(lambda x: (x[:4], x[5:])))
它returns一个关键错误
使用 df.dtypes returns:
NAME object
TMAX float64
TMIN float64
dtype: object
因此,虽然我的数据框清楚地显示了日期列,但它不在我的列列表中。当我在此之前将索引设置为 Date 时,没有错误。关于我做错了什么的想法?
您似乎已将 Date
设置为您的索引,因此,它自然不会显示为列之一。您现在可以使用 df.index
来引用它。
此外,我不建议对datetime
数据进行字符串操作。使用访问器并提取所需的日期组件。如果它不是 datetime
格式,请使用 pd.to_datetime
并转换它。
# don't run this line if the index is a DateTimeIndex already
y = pd.to_datetime(df.index, errors='coerce')
df['Year'], df['Month-Date'] = y.year, y.month
我正在尝试汇总一年中 2 个不同州的最低和最高温度。我的数据框中的列是日期、名称、Tmax、Tmin。
然而,当我尝试使用时:
df['Year'], df['Month-Date'] = zip(*df['Date'].apply(lambda x: (x[:4], x[5:])))
它returns一个关键错误
使用 df.dtypes returns:
NAME object
TMAX float64
TMIN float64
dtype: object
因此,虽然我的数据框清楚地显示了日期列,但它不在我的列列表中。当我在此之前将索引设置为 Date 时,没有错误。关于我做错了什么的想法?
您似乎已将 Date
设置为您的索引,因此,它自然不会显示为列之一。您现在可以使用 df.index
来引用它。
此外,我不建议对datetime
数据进行字符串操作。使用访问器并提取所需的日期组件。如果它不是 datetime
格式,请使用 pd.to_datetime
并转换它。
# don't run this line if the index is a DateTimeIndex already
y = pd.to_datetime(df.index, errors='coerce')
df['Year'], df['Month-Date'] = y.year, y.month