Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide multiple columns by another column in pandas

Tags:

python

pandas

I need to divide all but the first columns in a DataFrame by the first column.

Here's what I'm doing, but I wonder if this isn't the "right" pandas way:

df = pd.DataFrame(np.random.rand(10,3), columns=list('ABC'))  df[['B', 'C']] = (df.T.iloc[1:] / df.T.iloc[0]).T 

Is there a way to do something like df[['B','C']] / df['A']? (That just gives a 10x12 dataframe of nan.)

Also, after reading some similar questions on SO, I tried df['A'].div(df[['B', 'C']]) but that gives a broadcast error.

like image 424
itzy Avatar asked Dec 31 '15 03:12

itzy


People also ask

How do I divide multiple columns in pandas?

Method 2: Pandas divide two columns using div() function It divides the columns elementwise. It accepts a scalar value, series, or dataframe as an argument for dividing with the axis. If the axis is 0 the division is done row-wise and if the axis is 1 then division is done column-wise.

How do you do division in pandas?

Pandas DataFrame: div() functionThe div() function returns floating division of dataframe and other, element-wise (binary operator truediv). Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **. Any single or multiple element data structure, or list-like object.

How do I divide one data frame by another?

div() method divides element-wise division of one pandas DataFrame by another. DataFrame elements can be divided by a pandas series or by a Python sequence as well. Calling div() on a DataFrame instance is equivalent to invoking the division operator (/).


Video Answer


2 Answers

I believe df[['B','C']].div(df.A, axis=0) and df.iloc[:,1:].div(df.A, axis=0) work.

like image 110
Dthal Avatar answered Oct 13 '22 04:10

Dthal


do: df.iloc[:,1:] = df.iloc[:,1:].div(df.A, axis=0) 

This will divide all columns other than the 1st column with the 'A' column used as divisor.

Results are 1st column + all columns after / 'divisor column'.

like image 40
user17300673 Avatar answered Oct 13 '22 05:10

user17300673