I want to fill in the NaN values in a DataFrame (df) (var4) column based on a checklist (fillna_mean) using the average column value and var1 as an index. In the data core, I want them to match var1.
I tried to do this with fillna, but I do not make it work to the end. How can I do this in a reasonable way, using df.var1 as an index corresponding to fillna_mean.var1?
DF:
df = pd.DataFrame({'var1' : list('a' * 3) + list('b' * 2) + list('c' * 4) + list('d' * 3)
,'var2' : [i for i in range(12)]
,'var3' : list(np.random.randint(100, size = 12))
,'var4' : [1, 2, np.nan, 3, 2, np.nan, 1, 34, np.nan, np.nan, 12, 12]
})
fillna_mean:
fillna = pd.DataFrame({'var1' : ['a', 'b', 'c', 'd'],
'mean' : [1, 3.5, 6.5, 10]})
The end result is as follows:
var1 var2 var3 var4
a 0 69 1.0
a 1 17 2.0
a 2 83 1.0
b 3 12 3.0
b 4 36 2.0
c 5 68 6.5
c 6 13 1.0
c 7 30 34.0
c 8 23 6.5
d 9 82 10.0
d 10 32 12.0
d 11 19 12.0
Thanks in advance for entering!
/ swepab