tl;dr
Turn the SettingWithCopyWarning
into an explicit error that you are forced to fix by setting
import pandas as pd
pd.set_option("mode.chained_assignment", "raise")
Problem
pandas
is complaining to you with the following warning (which only shows up on first execution):
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Solution
Use pd.set_option("mode.chained_assignment", "raise")
to force yourself to actually fix the underlying piece of offending code.
Most often you will need to explicitly call .copy()
on a sub-dataframe you want to manipulate, particularly when you want to ensure that changes you make to the “slice” of the DataFrame do not propagate back to the original object.
Credit to this article for explaining the problem and solution.