在使用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)
答案 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)