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:
JavaScript
x
2
1
df['quantity'] *= -1 # trying to multiply each row's quantity column with -1
2
gives me a warning:
JavaScript
1
3
1
A value is trying to be set on a copy of a slice from a DataFrame.
2
Try using .loc[row_indexer,col_indexer] = value instead
3
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:
JavaScript
1
3
1
for idx, row in df.iterrows():
2
df.loc[idx, 'quantity'] *= -1
3
EDIT:
I am running 0.16.2
of Pandas
full trace:
JavaScript
1
7
1
SettingWithCopyWarning:
2
A value is trying to be set on a copy of a slice from a DataFrame.
3
Try using .loc[row_indexer,col_indexer] = value instead
4
5
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
6
self.obj[item] = s
7
Advertisement
Answer
Here’s the answer after a bit of research:
JavaScript
1
2
1
df.loc[:,'quantity'] *= -1 #seems to prevent SettingWithCopyWarning
2