How to Divide a Number of Columns by One Column

Divide multiple columns by another column in pandas

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

Divide multiple columns by a fix number in pandas

You can use broadcasting:

df[['B','C']] /= 1000

Output:

   A    B    C   D
0 1 0.1 2.0 10
1 2 0.2 3.0 0
2 3 0.3 4.0 20
3 4 0.4 5.0 40
4 5 0.5 4.0 24
5 6 0.6 2.0 23

How to divide all columns by one column in BigQuery

As Suggested by @Aishwary, you can write a script to get the list of columns using INFORMATION_SCHEMA and then iterate over the list of columns to get the desired result.

Dividing one column in a dataframe by a number while bringing back all other columns in the dataframe

You can do:

df['C']= df['C']/4

It will divide the column C by 4 while keeping other columns same.

You are getting the output column C only because you are saving column C changed only:

df['C']= df[['C']].div(4, axis=0)

This may give you the exact result

how to divide all the values of columns with respect of a row?

Operating under the assumption that the id of the last col is unique:

If you need to iterate over large numbers of columns

from pyspark.sql.functions import col, when
df = spark.createDataFrame(
[
('A',2,3),
('B',8,9),
('C',7,5),
('fre',12,13)
],
['col1','col2','col3']
)

# Get last row
lr = df.tail(1)[0]
# Get last row col1 for otherwise
l_col1 = lr[0]

for c, v in zip(df.columns[1:], lr[1:]):
df = df.withColumn(c, when(col('col1')!=l_col1, col(c)/v).otherwise(v))

If you want to divide the last column as well

from pyspark.sql.functions import col, when
df = spark.createDataFrame(
[
('A',2,3),
('B',8,9),
('C',7,5),
('fre',12,13)
],
['col1','col2','col3']
)

# Get last row
lr = df.tail(1)[0]
# Get last row col1 for
l_col1 = lr[0]

for c, v in zip(df.columns[1:], lr[1:]):
df = df.withColumn(c, col(c)/v)

Divide several columns by several other columns in Pandas

You can do the division in one run using numpy:

df[df.filter(like='X').columns.str.replace('X', 'Z')] = df.filter(like='X').to_numpy() / df.filter(like='Y').to_numpy()

Result:

   X_1  X_2  Y_1   Y_2       Z_1       Z_2
A 5 6 479 964 0.010438 0.006224
B 27 51 298 474 0.090604 0.107595
C 26 173 598 1854 0.043478 0.093312
D 71 183 693 1855 0.102453 0.098652

How to divide the value of pandas columns by the other column

The / operator for dv seems equal to div with default axis "columns". Set the axis to "index", then it'll work.

df = df.div(df.QT, axis='index')

Another tricky way is to transpose it first, divide it, and then transpose back:

df = (df.T / df.QT).T


Related Topics



Leave a reply



Submit