在熊猫系列中设置日期时间值时的SettingWithCopyWarning

时间:2018-12-14 02:37:18

标签: python python-3.x pandas

在使用iloc在熊猫系列中设置值时,我得到了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. 如何避免这种情况? (除了关闭警告)

1 个答案:

答案 0 :(得分:1)

确实是造成问题的这部分:

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

使用copy

明确告诉熊猫这是它自己的系列
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)