2

I am getting a SettingWithCopyWarning when setting a value in a pandas Series using iloc. I am using pandas 0.21.1 and 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')

output:

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. Why does this happen? I am setting a value in the original series
  2. What can I do to avoid this? (Other than turning off the warning)

1 Answer 1

3

it is really this part that is causing the problem:

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

explicitly tell pandas that this is its own series by using 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)
Sign up to request clarification or add additional context in comments.

1 Comment

Got it thanks. I got mixed up between the documentation of Series.dt.tz_localize and Series.tz_localize.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.