Pandas切片失败,并显示DatetimeIndex标签列表

时间:2018-04-30 18:41:15

标签: python pandas datetime slice

我有一个12x3数据框,存储2017年月平均,最高和最低温度:

import pandas as pd

tavg = pd.Series([55.8, 57.2, 61.0, 63.6, 63.3, 66.7, 71.7, 72.0, 71.5, 71.5, 65.6, 61.4])
tmax = pd.Series([62.7, 62.6, 69.3, 71.9, 69.4, 72.6, 77.5, 77.3, 78.5, 80.4, 73.7, 72.4])
tmin = pd.Series([48.8, 51.8, 52.8, 55.4, 57.1, 60.9, 65.8, 66.8, 64.6, 62.5, 57.3, 50.3])

temp_df = pd.DataFrame()
temp_df['TAVG'] = tavg
temp_df['TMIN'] = tmin
temp_df['TMAX'] = tmax

dates = pd.date_range(start='2017-01-01', end='2017-12-01', freq='MS')

temp_df.index = dates

我想按标签分割日期列表,例如2017-01-01和2017-05-01。

单独切片这些日期的工作正常:

temp_df.loc['2017-01-01']

TAVG    55.8
TMIN    48.8
TMAX    62.7
Name: 2017-01-01 00:00:00, dtype: float64

temp_df.loc['2017-05-01']

TAVG    63.3
TMIN    57.1
TMAX    69.4
Name: 2017-05-01 00:00:00, dtype: float64

但是使用这些日期列表进行切片会引发KeyError:

temp_df.loc[['2017-01-01', '2017-05-01']]

"KeyError: "None of [['2017-01-01', '2017-05-01']] are in the [index]"

使用DatetimeIndex时,是否有使用索引标签列表切片的特殊技巧?

1 个答案:

答案 0 :(得分:2)

切片失败,因为索引的类型为Timestamp。代码temp_df.loc[['2017-01-01', '2017-05-01']]查找String标签。使用以下代码将其解析为Timestamp

temp_df.loc[[pd.Timestamp('2017-01-01'), pd.Timestamp('2017-05-01')]]

输出:

            TAVG    TMIN    TMAX
2017-01-01  55.8    48.8    62.7
2017-05-01  63.3    57.1    69.4

要使代码生效,您需要将索引类型更改为str

temp_df.index = temp_df.index.astype(str)
temp_df.loc[['2017-01-01', '2017-05-01']]

输出:

            TAVG    TMIN    TMAX
2017-01-01  55.8    48.8    62.7
2017-05-01  63.3    57.1    69.4