【发布时间】:2015-01-02 00:11:02
【问题描述】:
我有一个以字符串格式导入的 pandas DataFrame 中的字段。 它应该是一个日期时间变量。 如何将其转换为日期时间列,然后根据日期进行过滤。
例子:
- 数据帧名称:raw_data
- 列名:Mycol
- 价值 列中的格式:'05SEP2014:00:00:00.000'
【问题讨论】:
我有一个以字符串格式导入的 pandas DataFrame 中的字段。 它应该是一个日期时间变量。 如何将其转换为日期时间列,然后根据日期进行过滤。
例子:
【问题讨论】:
使用to_datetime 函数,指定format 来匹配您的数据。
raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
【讨论】:
format 参数不是必需的。 to_datetime 很聪明。继续尝试,不要尝试匹配您的数据。
SettingWithCopyWarning 使用@darth-behfans stackoverflow.com/a/42773096/4487805
infer_datetime_format=True 也可以将解析速度提高到 ~5-10 倍(根据 pandas 文档)。
如果您有多个要转换的列,您可以执行以下操作:
df[["col1", "col2", "col3"]] = df[["col1", "col2", "col3"]].apply(pd.to_datetime)
【讨论】:
states_df[['from_datetime','to_datetime','timestamp']].apply(lambda _: pd.to_datetime(_,format='%Y-%m-%d %H:%M:%S.%f', errors='coerce'))
您可以使用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
【讨论】:
使用 pandas to_datetime 函数将列解析为 DateTime。此外,通过使用infer_datetime_format=True,它会自动检测格式并将提到的列转换为日期时间。
import pandas as pd
raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], infer_datetime_format=True)
【讨论】:
infer_datetime_format=True 可以将解析速度提高约5-10 倍。
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
我猜这是由于一些链接索引造成的。
【讨论】:
节省时间:
raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'])
【讨论】:
请务必注意,pandas.to_datetime 几乎不会返回 datetime.datetime。来自the docs
块引用
Returns datetime
If parsing succeeded. Return type depends on input:
list-like: DatetimeIndex
Series: Series of datetime64 dtype
scalar: Timestamp
In case when it is not possible to return designated types (e.g. when any element
of input is before Timestamp.min or after Timestamp.max) return will have
datetime.datetime type (or corresponding array/Series).
块引用
【讨论】: