rasputin
rasputin

Reputation: 324

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.

Upvotes: 0

Views: 945

Answers (2)

rasputin
rasputin

Reputation: 324

Try this:

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

Upvotes: 1

Omid Roshani
Omid Roshani

Reputation: 1183

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)

Upvotes: 0

Related Questions