7

我有一个数据框,其中列的名称是字符串形式的日期(年月)。如何将这些名称转换为日期时间格式?我试过这样做:

new_cols = pd.to_datetime(df.columns)
df = df[new_cols]

但我得到了错误:

KeyError: "DatetimeIndex(
['2000-01-01', '2000-02-01',
 '2000-03-01', '2000-04-01',
 '2000-05-01', '2000-06-01', 
'2000-07-01', '2000-08-01',               
'2000-09-01', '2000-10-01',
'2015-11-01', '2015-12-01', 
'2016-01-01', '2016-02-01',
'2016-03-01', '2016-04-01', 
'2016-05-01', '2016-06-01',
'2016-07-01', '2016-08-01'],
dtype='datetime64[ns]', length=200, freq=None) not in index"

谢谢!

4

2 回答 2

21

如果按loc列选择值未更改,则获取KeyError.

所以你需要将输出分配给columns

df.columns = pd.to_datetime(df.columns)

样本:

cols = ['2000-01-01', '2000-02-01', '2000-03-01', '2000-04-01', '2000-05-01']
vals = np.arange(5)
df = pd.DataFrame(columns = cols, data=[vals])
print (df)
   2000-01-01  2000-02-01  2000-03-01  2000-04-01  2000-05-01
0           0           1           2           3           4

print (df.columns)
Index(['2000-01-01', '2000-02-01', '2000-03-01', '2000-04-01', '2000-05-01'], dtype='object')

df.columns = pd.to_datetime(df.columns)

print (df.columns)
DatetimeIndex(['2000-01-01', '2000-02-01', '2000-03-01', '2000-04-01',
               '2000-05-01'],
              dtype='datetime64[ns]', freq=None)

也可以转换为期间:

print (df.columns)
Index(['2000-01-01', '2000-02-01', '2000-03-01', '2000-04-01', '2000-05-01'], dtype='object')

df.columns = pd.to_datetime(df.columns).to_period('M')

print (df.columns)
PeriodIndex(['2000-01', '2000-02', '2000-03', '2000-04', '2000-05'],
             dtype='period[M]', freq='M')
于 2017-01-16T13:48:51.767 回答
2

作为对 jezrael 答案的扩展,原始代码将尝试通过存储在 new_cols 中的数组对 df 数组进行切片并将结果存储为 df - 但由于这些值在 df 中不存在,但它返回一个错误,表明它可以' t 找到要切片的索引。

因此,您需要声明您正在更改列的名称,如 jezrael 的回答。

于 2017-01-16T13:58:36.573 回答