Search code examples
pythonpandasdataframemultiplication

Multiply random columns by another column


I have a list that is filled by random header names of a df.

listado=['A','J']

listado can have 1 value only.

if that listado has values then I would like it to multiply those columns in the df by another dataframe made from 1 column called valores.

valores=df2.values

df2=
   value
0    2 
1    4  
2    3

the df is as it follows:

df=
    A  B  C  J  K
0   3  2  5  4  7  
1   5  5  5  5  5
2   9  8  5  1  7

Then the desired output is to multiply columns A and J by the values of df2:

    A  B  C  J   K
0   6  2  5  8   7  
1  20  5  5  20  5
2  27  8  5  3   7

I was trying something like this in order to multiply the specific columns obtained in the list:

if listado:
    valores=df2.values
    for units in listado:
        df1[units]=df1[units]*valores
 return df1

but it

 raise Exception('Data must be 1-dimensional')

and the same when I tried :

if listado:
    valores=df2.values
    for i in range(len(listado)):
        df1[listado[i]]=df1[listado[i]]*valores
 return df1

How could I obtain the desired output?


Solution

  • Use conditional .loc and mul on axis=0

    In [496]: df.loc[:, listado] = df.loc[:, listado].mul(df2['value'], axis=0)
    
    In [497]: df
    Out[497]:
        A  B  C   J  K
    0   6  2  5   8  7
    1  20  5  5  20  5
    2  27  8  5   3  7