0

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.

rasputin
  • 25
  • 4
  • It should be working for now, in future you have to adjust according to the Warning message. – Talha Tayyab Jul 14 '23 at 16:00
  • You're using `df.loc[]`, right? But the error message mentions `iloc[]`. Can you double check that you're using loc when you got that error? – Nick ODell Jul 14 '23 at 16:56
  • @NickODell Yes, I'm using df.loc[]. The error message applies to both df.loc and df.iloc. See [this update](https://pandas.pydata.org/docs/whatsnew/v1.5.0.html#inplace-operation-when-setting-values-with-loc-and-iloc) – rasputin Jul 14 '23 at 17:10

2 Answers2

0

You can use this this alternative:

import pandas as pd

mask = df['date'] < "2023-06-01"
df.loc[mask, 'date'] = df.loc[mask, 'date'] + pd.DateOffset(years=1)
Omid Roshani
  • 1,083
  • 4
  • 15
0

Try this:

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