Home > Net >  Python - multiply columns based on values in other column, and values located in the first row of th
Python - multiply columns based on values in other column, and values located in the first row of th

Time:02-20

I have a dataframe with hundreds of rows. I want to fill the NaN starting from T1 column, by multiplying the value in the same row in weight column with the value in the first row within the same T column (sorry if my wording is hard to understand). Below is a sample of the original dataframe:

    ID  weight  T1          T2          T3          T4
0   A   1.00    1000        2000        3000        4000
1   B   0.04    NaN         NaN         NaN         NaN 
2   C   0.01    NaN         NaN         NaN         NaN 
3   D   0.06    NaN         NaN         NaN         NaN 

An example of the multiplication I want:

    ID  weight  T1          T2          
0   A   1.00    1000        2000        
1   B   0.03    0.03*1000   0.03*2000       
2   C   0.02    0.02*1000   0.02*2000           
3   D   0.07    0.07*1000   0.07*2000           

How can this be done?

CodePudding user response:

Extract values from weight and 1st row of T columns and then do an outer product:

tcols = df.filter(like='T').columns
df[tcols] = np.outer(df.weight, df[tcols].loc[0])

df
  ID  weight      T1      T2      T3      T4
0  A    1.00  1000.0  2000.0  3000.0  4000.0
1  B    0.04    40.0    80.0   120.0   160.0
2  C    0.01    10.0    20.0    30.0    40.0
3  D    0.06    60.0   120.0   180.0   240.0
  • Related