ChatGPT解决这个技术问题 Extra ChatGPT

将 Pandas 列转换为 DateTime

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

例子:

数据帧名称:raw_data

栏目名称:Mycol

列中的值格式:'05SEP2014:00:00:00.000'


a
atwalsh

使用 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
如果您只想要时间而不想要日期怎么办?
不是很聪明。即使某些列明确地采用 dayfirst=True 格式,对于同一列中的其他列,它仍将默认为 dayfirst=False。因此,使用显式格式规范或至少使用 dayfirst 参数更安全。
省略格式字符串可能会导致此操作因大量记录而变慢。 This answer 讨论了原因。如果您不包含格式字符串,看起来 infer_datetime_format=True 也可以将解析速度提高到 ~5-10 倍(根据 pandas 文档)。
V
Vlad Bezden

如果您有多个要转换的列,您可以执行以下操作:

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'))
m
mechanical_meat

您可以使用 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

谢谢!这很好,因为它更广泛适用,但另一个答案更直接。我很难决定我更喜欢哪个:)
我更喜欢这个答案,因为它产生一个 datetime 对象而不是 pandas.tslib.Timestamp 对象
R
RobC

使用 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 为我节省了很多时间。谢谢楼主!
很高兴帮助@Mike_Leigh !此外,根据 docs,在某些情况下,设置 infer_datetime_format=True 可以将解析速度提高约 5-10 倍。
不适用于我的日期格式“Jan-18”,它应该等于“%b-%Y”
@Pfinnn 如果您知道确切的日期格式,则可以使用以下代码:pd.to_datetime('Jan-18', format='%b-%y')。此外,对于 python strftime 备忘单,请参阅:strftime.org
P
Petter Friberg
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.loc[:,'Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S 。%F')
这对我有用: raw_data.loc[:,'Mycol'] = pd.to_datetime(raw_data.loc[:,'Mycol'], format='%d%b%Y:%H:%M:%S。 %F')
df2.loc[:,'datetime'] = pd.to_datetime(df2['datetime']) /usr/lib/python3/dist-packages/pandas/core/indexing.py:543: SettingWithCopyWarning: 一个值试图在 DataFrame 的切片副本上设置。尝试改用 .loc[row_indexer,col_indexer] = value 查看文档中的注意事项:pandas.pydata.org/pandas-docs/stable/… self.obj[item] = s
或者只是在 df 副本上重置索引
G
Gil Baggio

省时间:

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'])

h
hotplasma

需要注意的是,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).

块引用


这没有提供问题的答案。一旦你有足够的reputation,你就可以comment on any post;相反,provide answers that don't require clarification from the asker。 - From Review