2

Let's say I have a numpy df such as

X = pd.DataFrame(np.array([
[  9.,   12.,   4.],
[  1.,  31.,   3.],
[  6.,   4.,  1.]]) )

I want to divide each entry by the row sum * column sum. I know I can get row and column sum, respectively, using X.sum() and X.sum(1) but I don't know how to do the operation I'm seeking aside from looping through each entry brute force.

2 Answers 2

1

Use broadcasting:

import pandas as pd
import numpy as np

X = pd.DataFrame(np.array([
    [9., 12., 4.],
    [1., 31., 3.],
    [6., 4., 1.]]))

X_arr = X.values
mult = X_arr.sum(1)[:, None] * X_arr.sum(0)

result = X / mult
print(result)

Output

          0         1         2
0  0.022500  0.010213  0.020000
1  0.001786  0.018845  0.010714
2  0.034091  0.007737  0.011364
Sign up to request clarification or add additional context in comments.

Comments

0

You just need to divide twice:

# axis='rows' divide row-wise
x.div(x.sum()).div(x.sum(1), axis='rows')

Output:

          0         1         2
0  0.022500  0.010213  0.020000
1  0.001786  0.018845  0.010714
2  0.034091  0.007737  0.011364

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.