无法将现有 Dataframe 中的多个 Pandas 列从 Object 转换为 Datetime 类型(就地更新)

Cannot convert multiple Pandas columns from Object to Datetime type in the existing Dataframe (inplace update)

我有一个包含十多列的 Pandas 数据框,其中大部分列都是 Pandas 'object' 类型。

我需要将这些列中的三个从 'object' 转换为 'datetime' 类型并写回现有数据框列(以执行 ' 就地更新').

我仅将以下代码用作一栏的起点,并计划将其扩展到其他两栏,但它不起作用。

bigframe”数据框有许多重复行。我正在删除基于“incidentId”的重复行,并将唯一行分配给下面的“alerts”。

alerts = bigframe.drop_duplicates(subset=['incidentId'])
alerts['firstEventTime'] = pd.to_datetime(alerts['firstEventTime'])

alerts['firstEventTime']的内容类似于'2021-01-2722:34:05.991031+00: 00'

我收到以下警告,但代码的执行已完成且没有错误。

"试图在 DataFrame 的切片副本上设置一个值。 尝试使用 .loc[row_indexer,col_indexer] = value 代替 "

当我键入“alerts.dtypes”时,我仍然看到该列列为“object'类型。因此,我假设由于某种原因操作没有写回原始数据帧。

我在网上搜索了一下,上面列出的代码应该可以工作,但没有。所以我一定做错了什么,但我找不到它。你能告诉我我做错了什么吗?

谢谢!

这里有两个不相关的问题;

#1 DataFrame.drop_duplicates returns a slice of the existing df, not a new df. You can avoid the warning by copy将结果明确地写入新的 df。

#2 pandas datetime dtype 无法处理一个系列中的混合 UTC 偏移量。在这种情况下,它回退到使用 Python 的日期时间,即元素的类型为 datetime.datetime,显示为 'object'。您可以通过使用关键字 utc=True.

转换为 UTC 来处理此问题

例如:

bigframe = pd.DataFrame({'incidentId': [1,1,2],
                         'firstEventTime': ['2021-01-27 22:34:05.991031+00:00',
                                            '2021-01-27 22:34:05.991031+00:00', 
                                            '2022-01-18 20:34:52']})

# avoid the warning by explicitly calling .copy():
alerts = bigframe.drop_duplicates(subset=['incidentId']).copy()

# now convert to datetime in UTC, to get a datetime64[ns] dtyped Series:
alerts['firstEventTime'] = pd.to_datetime(alerts['firstEventTime'], utc=True)

alerts['firstEventTime']
# 0   2021-01-27 22:34:05.991031+00:00
# 2          2022-01-18 20:34:52+00:00
# Name: firstEventTime, dtype: datetime64[ns, UTC]

请注意,如果未指定 UTC 偏移量,pandas 将假定输入为 UTC。