'replace null values using other records (Python)

I have a dataframe as below:

name    category
----    ----
C58     UP 
D96     DOWN
C58     null

There are lots of null values in category column while they can easily be replaced using other rows for example we know C58 is UP so the null value shoud be UP.



Solution 1:[1]

IIUC, you want to fill the missing values in category by the values elsewhere in the same column with the same "name". Then you could use groupby + ffill:

df['category'] = df.groupby('name')['category'].ffill()

If each name has exactly one category value, you could also use groupby + transform('first'):

df['category'] = df.groupby('name')['category'].transform('first')

Output:

  name category
0  C58       UP
1  D96     DOWN
2  C58       UP

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1