Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python astype(str) gives SettingWithCopyWarning and requests I use loc

Using this simple line of code, I keep on getting a SettingWithCopyWarning error that than carries through my whole code.

#make email a string
df['Email Address'] = df['Email Address'].astype(str)

C:\Users\xxx\AppData\Local\Continuum\Anaconda2\lib\site-packages\ipykernel\__main__.py:2: 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: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  from ipykernel import kernelapp as app

I went through the documentation, but can't make it work with loc. The code below is wrong.

df.loc['Email Address'] = df.loc['Email Address'].astype(str)

Please excuse if this is a duplicate question - I searched it on stackoverflow, but couldn't find one that addresses loc and astype.

like image 453
jeangelj Avatar asked Jul 11 '17 14:07

jeangelj


2 Answers

Your issue isn't with how you are making the assignment. It is with the dataframe prior to assignment. At some point prior to the assignment, you created df in such a way that it became a view into another dataframe. You can verify this with bool(df.is_copy)

If you are ok with df being a separate thing with no linkages to data in other dataframes...

df = df.copy()

Then proceed to make your assignment.

like image 114
piRSquared Avatar answered Oct 08 '22 10:10

piRSquared


Update 03/21

I believe this is the correct solution with loc

df.loc[:, 'Email Address'].astype(str)

like image 37
Pysnek313 Avatar answered Oct 08 '22 10:10

Pysnek313