Pandas 2.1.0 warning ''The 'method' keyword in Series.replace is deprecated and will be removed in a future version''

4k Views Asked by At

I have a pandas line of code that gives me a future deprecation warning as stated in the title and I can't find in the pandas documentation how to modify it in order to remove the warning. The line of code is the following:

df['temp_open']=df['temp_open'].replace('',method='ffill')

Any help would be greatly appreciated.

I tried to fill blanks and it works, but I would like to get rid of the warning.

3

There are 3 best solutions below

0
Timeless On BEST ANSWER

You can do this instead :

df["temp_open"] = df["temp_open"].replace("", None).ffill()

And if you want to keep the nulls (if any) untouched, you can use :

df["temp_open"] = (
    df["temp_open"].replace("", None).ffill().where(df["temp_open"].notnull())
)

Output :

print(df)

  temp_open
0         A
1         A
2       NaN
3         B
4         C
5         C

Used input :

df = pd.DataFrame({"temp_open": ["A", "", None, "B", "C", ""]})
1
letdatado On

The warning you're encountering is likely related to the use of the method parameter with an empty string ''. In older versions of Pandas, using an empty string '' as the method parameter for the replace method was allowed, but it's no longer supported in newer versions of Pandas.

To remove the warning and update your code to use the correct syntax, you can use the appropriate method for forward filling missing values. You can use fillna with the method parameter set to 'ffill' instead.

df['temp_open'] = df['temp_open'].fillna(method='ffill')

0
mlokos On

Argument method from function replace is being depreciated in favour of a function ffill.

Docs:

What you have to do is to refactor your code in a way @Timeless have answered your question.