0

Both the .loc and .contains functions return a dataframe object. The pandas documentation states that to reassign a value to each row in the column, I should use .loc, but when combined with .contains I get this warning:

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

However, the process works and I get the desired value reassignment for each row in the dataframe's column. How can I avoid this warning?

#works
df.loc[df["matchType"]=='duo',["matchType"]]='duo'

#warning thrown but still works
df.loc[df["matchType"].str.contains('duo'),["matchType"]]='duo'
Nick ODell
  • 15,465
  • 3
  • 32
  • 66
Bugbeeb
  • 2,021
  • 1
  • 9
  • 26
  • I am unable to reproduce the issue. Neither of the assignment statements produces any warning when I run them (using pandas version 0.24.2). – Xukrao Apr 14 '19 at 22:18
  • [This](https://www.dataquest.io/blog/settingwithcopywarning/) link will help. The ultimate reason a `SettingWithCopyWarning` is raised is likely an earlier line of code; this snippet alone should cause no problems. – gmds Apr 15 '19 at 01:17

1 Answers1

2

I did some tweaking and removed the brackets around the column indexer since it was a single column. I also noticed a line in my code that could also be responsible for the warning, like gmds suggested, and I simplified things:

df.loc[(df['matchType'].str.contains('solo')==False) & 
(df['matchType'].str.contains('duo')==False),"matchType"]="other"
-->
df.loc[df['matchType'].str.contains('solo|duo')==False),"matchType"]="other"
Bugbeeb
  • 2,021
  • 1
  • 9
  • 26