I'm not even going to list the number of duplicate questions on SO about SettingWithCopyWarning. I'm simply attempting to convert a string field to a datetime field for an entire dataframe. Following all the advice I've found using df.loc[]
I'm still getting that error.
Here's the code.
import pandas as pd
df = pd.read_csv("data/cat-1.csv")
# kill empty rows
trimmed_df = df.dropna(how="all")
# proper DateTime
trimmed_df.loc[:,'Transaction Date'] = pd.to_datetime(trimmed_df['Transaction Date'])
Followed by the ubiquitous error:
/usr/local/anaconda3/lib/python3.8/site-packages/pandas/core/indexing.py:1745: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
isetter(ilocs[0], value)
The crazy part is that I'm doing exactly what the error is telling me to do, and yet I'm STILL getting the error.
The other crazy part is if you search SO for "pandas convert column to datetime" you get a bunch of answers like in this question, which all completely ignore .loc
and just assign to the column and presumably don't throw errors (there's never a mention of this error in the comments)
There are also plenty of solutions using lambda functions but before I go down that rathole I want to understand why my code throws the warning. It looks like I can avoid the warning by using .copy()
when I create trimmed_df
, or skip assigning the dropna()
to a new variable, but I kind of like the self-documenting "functional" feel of creating these variable aliases to show how my dataframe is being transformed. I'm not sure if this is idiomatic Python or not.
As I rubberduck this, I suspect it's going to be a case of "suck it up" in the comments (go ahead, I won't mind the trolling) but I've got to believe that there's a nice way of disambiguating what my intention is here so that Python doesn't feel the need to save me from myself with this warning, without resorting to unnecessary transformation functions etc.
Am I missing something?