pythonpython-3.xpandasdataframepandas-settingwithcopy-warning

How to fix deprecation warning when setting on a slice


I'm trying to add a year to each observation in a pandas dataframe until each observation is within a specified date range.

    for i in range(0,3):
        df.loc[df['date'] < "2023-06-01", 'date'] = df['date'] + pd.DateOffset(years=1)

I'm getting this warning.

DeprecationWarning: In a future version, `df.iloc[:, i] = newvals`
will attempt to set the values inplace instead of always setting
a new array. To retain the old behavior, use either
`df[df.columns[i]] = newvals` or, if columns are non-unique, 
`df.isetitem(i, newvals)`

How can I fix this? I've tried many things, but I can't seem to get around setting on a slice, and every method I try throws either the DeprecationWarning or SettingWithCopyWarning.


Solution

  • Try this:

    for i in range(0,3):
        df['date'].mask(df['date'] < '2023-06-01', 
                        df['date'] + pd.DateOffset(years=1), inplace=True)