1

I have a Pandas DataFrame with a few columns, but I want to manipulate all of values in a single column (conditionally), like this:

df[my_column] = df[my_column].apply(lambda x: -float(x))

This works, but Pandas gives me a SettingWithCopyWarning.

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

Is there a problem with the way I'm going about manipulating this column?

Kieran
  • 25
  • 3

1 Answers1

3

The problem occurs earlier in your code. df is probably a slice of another dataframe and pandas is warning you not to make a modification of df because it is a copy of that other dataframe.

The easiest solution when you want to subset a dataframe and manipulate further is to use the .copy() method.

df = df_original.copy()

now you can apply code like:

df[my_column] = xxx

without a SettingWithCopyWarning.

Mark Andersen
  • 868
  • 6
  • 8