Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Pandas Dataframe how to multiply entire column with a scalar

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 
like image 883
labheshr Avatar asked Nov 17 '15 22:11

labheshr


People also ask

How do you multiply a value in a DataFrame in Python?

The mul() method multiplies each value in the DataFrame with a specified value. The specified value must be an object that can be multiplied with the values of the DataFrame.

How do you multiply in a data frame?

mul() function return multiplication of dataframe and other element- wise. This function essentially does the same thing as the dataframe * other, but it provides an additional support to handle missing values in one of the inputs. Example #1: Use mul() function to find the multiplication of a dataframe with a series.

What is the pandas method of getting fast access to a scalar for DataFrame DF?

If you only want to access a scalar value, the fastest way is to use the at and iat methods, which are implemented on all of the data structures.


1 Answers

try using apply function.

df['quantity'] = df['quantity'].apply(lambda x: x*-1) 
like image 98
maswadkar Avatar answered Oct 13 '22 00:10

maswadkar