将to_datetime应用于除index之外的所有列

时间:2017-02-18 20:24:13

标签: python pandas datetime dataframe

我有一个DataFrame,它有一个索引(uid)和9个变量,这些变量是当前作为字符串的日期。

我设法用pd.to_datetime将它们转换为日期时间,但是我想对所有列执行此操作,而不是逐个编写所有列的命令,如下所示:

initData['invited'] = pd.to_datetime(initData['invited'], dayfirst = True)
initData['sign_up'] = pd.to_datetime(initData['sign_up'], dayfirst = True)
initData['card_activated'] = pd.to_datetime(initData['card_activated'], dayfirst = True)

我怎样才能更优雅?我尝试了.apply,但是我收到错误,因为它试图将数据帧索引转换为datetime。

1 个答案:

答案 0 :(得分:1)

使用apply

initData = initData.apply(pd.to_datetime, dayfirst=True)
#same as
#initData = initData.apply(lambda x: pd.to_datetime(x, dayfirst = True))

样品:

initData = pd.DataFrame({'A':['01-01-2017','02-01-2017','03-01-2017'],
                   'B':['05-01-2017','06-01-2017','07-01-2017'],
                   'C':['01-01-2017','02-01-2017','03-01-2017']})

print (initData)
            A           B           C
0  01-01-2017  05-01-2017  01-01-2017
1  02-01-2017  06-01-2017  02-01-2017
2  03-01-2017  07-01-2017  03-01-2017

initData = initData.apply(pd.to_datetime, dayfirst=True)

print (initData)
           A          B          C
0 2017-01-01 2017-01-05 2017-01-01
1 2017-01-02 2017-01-06 2017-01-02
2 2017-01-03 2017-01-07 2017-01-03

print (initData.dtypes)
A    datetime64[ns]
B    datetime64[ns]
C    datetime64[ns]
dtype: object