samedi 27 mars 2021

Dynamically multiplying multiple columns pandas

quick question:

Let's say I have the two dfs:

      line amount#1    line amount#2    line amount#3    line amount#4
--  ---------------  ---------------  ---------------  ---------------
 0               95           nan              nan                 nan
 2               60             8.99             8.99              nan
 6              500            20               10                 nan


      taxrate#1    taxrate#2    taxrate#3    taxrate#4
--  -----------  -----------  -----------  -----------
 0         0.21       nan          nan             nan
 2         0.09         0.09         0.09          nan
 6         0.21         0.09         0             nan

I want to multiply them by each other and create a new column called 'TaxSubAmount' per column, so 4 columns in total:

I've tried the following using list comprehension:

#TO-DO DYNAMICALLY UPDATE 
df1 = dflineamount.loc[:,'line amount#1':'line amount#4'].multiply(dftaxrate, axis="index")
df1.columns = ['TaxSubAmount{}'.format(x) for x in range(1, len(df1.columns) + 1)]

However, this does not work..

Output:

      TaxSub1    TaxSub2    TaxSub3    TaxSub4    TaxSub5    TaxSub6    TaxSub7    TaxSub8
--  ---------  ---------  ---------  ---------  ---------  ---------  ---------  ---------
 0        nan        nan        nan        nan        nan        nan        nan        nan
 2        nan        nan        nan        nan        nan        nan        nan        nan
 6        nan        nan        nan        nan        nan        nan        nan        nan

Wanted output:

      TaxSub1    TaxSub2    TaxSub3    TaxSub4    
--  ---------  ---------  ---------  ---------  
 0       19,95        nan        nan        nan  
 2        5,4        0,81        0,81        nan  
 6        105        1,8         0        nan  

Please help!

Aucun commentaire:

Enregistrer un commentaire