将Pandas列转换为DateTime


241

我在以字符串格式导入的pandas DataFrame中有一个字段。它应该是日期时间变量。如何将其转换为datetime列,然后根据日期进行过滤。

例:

  • 数据框名称:raw_data
  • 列名称:Mycol
  • 列中的值格式:“ 05SEP2014:00:00:00.000”

Answers:


430

使用该to_datetime函数,指定一种格式以匹配您的数据。

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

70
注意:format参数不是必需的。to_datetime很聪明 继续尝试,而不尝试匹配您的数据。
samthebrand '17

6
为了避免SettingWithCopyWarning使用@达斯- behfans stackoverflow.com/a/42773096/4487805
阿尔瓦罗·洛萨

3
如果您只想要时间而不想要日期怎么办?
FaCoffee '17

5
不是很聪明。即使某些列明确地采用dayfirst = True格式,对于同一列中的其他列,它仍将默认设置为dayfirst = False。因此,更安全地使用显式格式规范或至少使用dayfirst参数。
CPBL

10
省略格式字符串可能会使此操作的记录速度很慢。这个答案讨论了为什么。infer_datetime_format=True如果您不包含格式字符串,看起来还可以将解析速度提高到大约5-10倍(根据pandas文档)。
atwalsh

52

您可以使用DataFrame方法.apply()对Mycol中的值进行操作:

>>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
>>> df
                    Mycol
0  05SEP2014:00:00:00.000
>>> import datetime as dt
>>> df['Mycol'] = df['Mycol'].apply(lambda x: 
                                    dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
>>> df
       Mycol
0 2014-09-05

1
谢谢!这很好,因为它适用范围更广,但其他答案更为直接。我很难决定我更喜欢哪个:)
克里斯·克里斯(Chris)

2
我更喜欢这个答案,因为它产生了datetime对象,而不是pandas.tslib.Timestamp对象
wesanyer 2015年

25

如果要转换的列不止一个,则可以执行以下操作:

df[["col1", "col2", "col3"]] = df[["col1", "col2", "col3"]].apply(pd.to_datetime)

15
raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

可以,但是会导致Python警告:试图在DataFrame的切片副本上设置一个值。尝试.loc[row_indexer,col_indexer] = value改用

我猜这是由于一些链接索引。


2
我做了几次尝试,但仍然有效:raw_data.loc [:,'Mycol'] = pd.to_datetime(raw_data ['Mycol'],format ='%d%b%Y:%H:%M:%S 。%f')
pinegulf

9

使用pandas to_datetime函数将列解析为DateTime。另外,通过使用infer_datetime_format=True,它将自动检测格式并将提到的列转换为DateTime。

import pandas as pd
raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], infer_datetime_format=True)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.