How do I multiply each element of a given column of my dataframe with a scalar? (I have tried looking on SO, but cannot seem to find the right solution)
Doing something like:
df['quantity'] *= -1 # trying to multiply each row's quantity column with -1
gives me a 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
Note: If possible, I do not want to be iterating over the dataframe and do something like this...as I think any standard math operation on an entire column should be possible w/o having to write a loop:
for idx, row in df.iterrows():
df.loc[idx, 'quantity'] *= -1
EDIT:
I am running 0.16.2
of Pandas
full trace:
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 the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[item] = s
Note: for those using pandas 0.20.3 and above, and are looking for an answer, all these options will work:
which results in
A little late to the game, but for future searchers, this also should work:
I got this warning using Pandas 0.22. You can avoid this by being very explicit using the assign method:
Here's the answer after a bit of research:
The real problem of why you are getting the error is not that there is anything wrong with your code: you can use either
iloc
,loc
, orapply
, or*=
, another of them could have worked.The real problem that you have is due to how you created the df DataFrame. Most likely you created your df as a slice of another DataFrame without using
.copy().
The correct way to create your df as a slice of another DataFrame isdf = original_df.loc[some slicing].copy()
.The problem is already stated in the error message you got " 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"
You will get the same message in the most current version of pandas too.
Whenever you receive this kind of error message, you should always check how you created your DataFrame. Chances are you forgot the
.copy()
More recent pandas versions have the pd.DataFrame.multiply function.