pythonpandasnan

Conditional multiplication of DataFrames with NaN


I have two DataFrames

A =

0 1 2
0 0.5 0
0.1 0 0.2
0.2 0 0

and B =

0
1.0
1.0
NaN

I need to multiply each row of A by B element-wise, but I need the computation done so that the resulting dataframe shows a NaN only if the original element of A is 0.

If I do

A * B.transpose()

I get

0 1 2
0 0.5 NaN
0.1 0 NaN
0.2 0 NaN

but I need it to be

0 1 2
0 0.5 NaN
0.1 0 0.2
0.2 0 NaN
import pandas as pd

A = pd.DataFrame([[0, 0.5, 0], 
                  [0.1, 0, 0.2], 
                  [0.2, 0, 0]])

B = pd.DataFrame([1, 1, np.NaN])

Solution

  • IIUC you can try:

    out = A * B.T.values
    out[out.isna() & ~A.eq(0)] = A
    
    print(out)
    

    Prints:

         0    1    2
    0  0.0  0.5  NaN
    1  0.1  0.0  0.2
    2  0.2  0.0  NaN