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.
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.
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.
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 (/).
I believe df[['B','C']].div(df.A, axis=0)
and df.iloc[:,1:].div(df.A, axis=0)
work.
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'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With