Home > Enterprise >  how to replace nan value using the value of which from other rows with common column value
how to replace nan value using the value of which from other rows with common column value

Time:10-23

Using column B as the reference how can I replace NaN value

>>> a
A   B  
1   1     
Nan 3     
1   1    
Nan 1
Nan 2      
5   3       
1   1    
2   2 

I want result like this.

>> result 
A   B  
1   1     
5   3     
1   1    
1   1
2   2      
5   3       
1   1    
2   2   

I tried merging on the column b but couldn't figure out b=a.groupby('B').reset_index() dfM = pd.merge(a,b,on='B', how ='left')

CodePudding user response:

We need a map from values in column B to the values in A.

mapping = a.dropna().drop_duplicates().set_index("B")["A"]

It looks like this

B
1    1.0
3    5.0
2    2.0
Name: A, dtype: float64

Filling null values becomes irrelevant at this point. We can just map B to get column A

a["B"].map(mapping)

This gives you

0    1.0
1    5.0
2    1.0
3    1.0
4    2.0
5    5.0
6    1.0
7    2.0
Name: B, dtype: float64

Cast to int and use it to overwrite column A in your original dataframe if you need to.

  • Related