0

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?

2
  • Does your expected output include those Nan? If that's the case, what's the reasoning behind not being able to calculate a value for them? For example, (C, T2) might be 0.02*2000, right? Commented Feb 20, 2022 at 6:44
  • @aaossa no I don't want NaNs. Sorry if my second output made you confused (I'll edit it now). And yes (C, T2) should be 0.02*2000 Commented Feb 20, 2022 at 6:53

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.