Home > Software engineering >  Python: how how to divide elements of arrays based on condition?
Python: how how to divide elements of arrays based on condition?

Time:06-23

I have two arrays F and P of the same dimension

F = np.array([[1, 4, 5], 
    [-5, 180, 9],
    [200, 3, 7]])

P = np.array([[11, 3, 9], 
    [4, 2, 77],
    [33, 4, 66]])

I want to divide each element F(i,j) of the matrix F with each element P(i,j) of the matrix P only where F(i,j)<100.

np.where(F<100)
(array([0, 0, 0, 1, 1, 2, 2]), array([0, 1, 2, 0, 2, 1, 2]))

CodePudding user response:

This is a possible solution:

(F < 100) * F / P   (F >= 100) * F

or, equivalently:

((F < 100) / P   (F >= 100)) * F

Using data that you provided, you get this result:

array([[ 9.09090909e-02,  1.33333333e 00,  5.55555556e-01],
       [-1.25000000e 00,  1.80000000e 02,  1.16883117e-01],
       [ 2.00000000e 02,  7.50000000e-01,  1.06060606e-01]])

CodePudding user response:

You can use where condition with division, in my case I did F/P and not P/F

import pandas as pd
import numpy as np
              
F = np.array([[1, 4, 5], 
            [-5, 180, 9],
            [200, 3, 7]])

P = np.array([  [11, 3, 9], 
                [4, 2, 77],
                [33, 4, 66]])

# Construct pandas DataFrame instances

dataFrame1 = pd.DataFrame(data=F);

dataFrame2 = pd.DataFrame(data=P);


res = dataFrame1.div(dataFrame2).where(dataFrame1 < 100, dataFrame1);
  • Related