Home > Software design >  Multiply a column with a row
Multiply a column with a row

Time:02-02

I have a data frame like this

Name        Oil     Cream      Sales
A           0        900        43
B          12         0         76
C           0         9         48
D           3         0         33
E          12        98         91
Cur Sales  0.1       0.9       998

Now when I want to make this into a data frame something like when the value is 0 then I has to multiply for oil column 43 * 0.1 on A row, for a cream column on 0 (76 * 0.9) on B row and for Oil column on C row on 0 (48 * 01). Something like that.

Expected Output

Name       Oil     Cream      Sales
A          4.3                 43
B                   68.4       76
C          4.8                 48
D                   29.7       33
E                              91
Cur Sales  0.1      0.9       998

For numbers that are greater than 0 I did

df[df > 0] = " "

Which makes them blank but how do I multiply column value with row on that particular 0?

CodePudding user response:

Select all columns and indices without columns Sales and index Cur Sales, comapre by 1 and multiple by column and by row:

c = df.columns.drop(['Sales'])
i = df.index.drop(['Cur Sales'])
df.loc[i, c]  = df.loc[i, c].eq(0).mul(df['Sales'], axis=0).mul(df.loc['Cur Sales'])
print (df)
           Oil Cream  Sales
Name                       
A          4.3   0.0     43
B          0.0  68.4     76
C          4.8   0.0     48
D          0.0  29.7     33
E          0.0   0.0     91
Cur Sales  0.1   0.9    998
  •  Tags:  
  • Related