gpt4 book ai didi

python - 在 Pandas 系列中设置日期时间值时的 SettingWithCopyWarning

转载 作者:太空宇宙 更新时间:2023-11-04 02:10:47 24 4
gpt4 key购买 nike

使用 iloc 在 pandas 系列中设置值时,我收到 SettingWithCopyWarning。我正在使用 Pandas 0.21.1 和 python 3.6.7

import pandas as pd
from datetime import datetime
from pytz import timezone

tz = timezone('CET')
ambiguous_dst = True

expected_dt_series = pd.Series([
datetime(2018, 10, 28, 1),
datetime(2018, 10, 28, 2),
datetime(2018, 10, 28, 3),
datetime(2018, 10, 28, 4),
])
expected_dt_series = expected_dt_series.dt.tz_localize(
tz, ambiguous='NaT')

expected_dt_series.iloc[1] = tz.localize(
datetime(2018, 10, 28, 2), is_dst=ambiguous_dst) # <- line that causes error

expected_dt_series = expected_dt_series.astype('object')

输出:

SettingWithCopyWarning: modifications to a method of a datetimelike object are not supported and are discarded. Change values on the original.
self._setitem_with_indexer(indexer, value)
x.py:17: SettingWithCopyWarning: modifications to a method of a datetimelike object are not supported and are discarded. Change values on the original.
datetime(2018, 10, 28, 2), is_dst=ambiguous_dst)
  1. 为什么会这样?我在原始系列中设置一个值
  2. 我该怎么做才能避免这种情况? (关闭警告除外)

最佳答案

确实是这部分导致了问题:

expected_dt_series = expected_dt_series.dt.tz_localize(tz, ambiguous='NaT')

使用copy明确告诉pandas这是它自己的系列

expected_dt_series = expected_dt_series.dt.tz_localize(
tz, ambiguous='NaT').copy()

expected_dt_series.iloc[1] = tz.localize(
datetime(2018, 10, 28, 2), is_dst=ambiguous_dst)

关于python - 在 Pandas 系列中设置日期时间值时的 SettingWithCopyWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53772797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com