Max
Max

Reputation: 471

How to dynamically fill column values in varying columns?

Imagine you have the following df:

line amount#1   line amount#2 line amount#3  line amount#4 lacheck line amount S
0   13.72                1.92   1.92         NaN            False       5            
1   13.72                1.93   NaN          NaN            False       10           
2   13.72                NaN    NaN          NaN            False       NaN   

I would like to dynamically fill the first line amount that is NaN with the line amount S.

So desired output would be:

line amount#1   line amount#2 line amount#3  line amount#4 lacheck line amount S
0   13.72                1.92   1.92         5              False       5            
1   13.72                1.93   10           NaN            False       10           
2   13.72                NaN    NaN          NaN            False       NaN   

Anyone who has any idea how to do this?

Please help!

Upvotes: 2

Views: 47

Answers (1)

jezrael
jezrael

Reputation: 862681

Idea is select first row by indexing with selecting first True by cumulative sum for working if no NaNs there and set values with chained masks with first value line amount S:

m = df.loc[0].isna()
m1 = m.cumsum().eq(1)

df.loc[0, m & m1] = df.loc[0, 'line amount S']
print (df)
   line amount#1  line amount#2  line amount#3  line amount#4  lacheck  \
0          13.72           1.92           1.92            5.0    False   
1          13.72           1.93            NaN            NaN    False   
2          13.72            NaN            NaN            NaN    False   

   line amount S  
0            5.0  
1           10.0  
2            NaN  

EDIT:

For set all rows use DataFrame.mask:

m = df.isna()
m1 = m.cumsum(axis=1).eq(1)
df = df.mask(m & m1, df['line amount S'], axis=0)

print (df)
   line amount#1  line amount#2  line amount#3  line amount#4  lacheck  \
0          13.72           1.92           1.92            5.0    False   
1          13.72           1.93          10.00            NaN    False   
2          13.72            NaN            NaN            NaN    False   

   line amount S  
0            5.0  
1           10.0  
2            NaN  

Upvotes: 1

Related Questions