使用 to_datetime
函数,指定 format 以匹配您的数据。
raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
如果您有多个要转换的列,您可以执行以下操作:
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
,它会自动检测格式并将提到的列转换为 DateTime。
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 警告 A value is trying to be set on a slice of a 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).
块引用
不定期副业成功案例分享
format
参数不是必需的。to_datetime
很聪明。继续尝试,不要尝试匹配您的数据。SettingWithCopyWarning
使用 @darth-behfans stackoverflow.com/a/42773096/4487805infer_datetime_format=True
也可以将解析速度提高到 ~5-10 倍(根据 pandas 文档)。