Replace NaN Value With A Median?
So I am trying to use Pandas to replace all NaN values in a table with the median across a particular range. I am working with a larger dataset but for example np.random.seed(0) rn
Solution 1:
You can use groupby.transform
and fillna:
cols = ['Val','Dist']
df[cols] = df[cols].fillna(df.groupby(df.Date.dt.floor('H'))
[cols].transform('median')
)
Output:
Date Val Dist
0 2020-09-24 00:00:00 1.764052 0.864436
1 2020-09-24 00:12:00 0.400157 0.653619
2 2020-09-24 00:24:00 0.978738 0.864436
3 2020-09-24 00:36:00 2.240893 0.864436
4 2020-09-24 00:48:00 1.867558 2.269755
5 2020-09-24 01:00:00 0.153690 0.757559
6 2020-09-24 01:12:00 0.950088 0.045759
7 2020-09-24 01:24:00 -0.151357 -0.187184
8 2020-09-24 01:36:00 -0.103219 1.532779
9 2020-09-24 01:48:00 0.410599 1.469359
10 2020-09-24 02:00:00 0.144044 0.154947
11 2020-09-24 02:12:00 1.454274 0.378163
12 2020-09-24 02:24:00 0.761038 0.154947
13 2020-09-24 02:36:00 0.121675 0.154947
14 2020-09-24 02:48:00 0.443863 -0.347912
15 2020-09-24 03:00:00 0.333674 0.156349
16 2020-09-24 03:12:00 1.494079 1.230291
17 2020-09-24 03:24:00 -0.205158 1.202380
18 2020-09-24 03:36:00 0.313068 -0.387327
19 2020-09-24 03:48:00 0.323371 -0.302303
Solution 2:
You can use a groupby -> transform
operation, while also utilizing the pd.Grouper
class to perform the hourly conversion. This will essentially create a dataframe with the same shape as your original with the hourly medians. Once you have this, you can directly use DataFrame.fillna
hourly_medians = df.groupby(pd.Grouper(key="Date", freq="H")).transform("median")
out = df.fillna(hourly_medians)
print(out)
Date Val Dist
0 2020-09-24 00:00:00 1.764052 0.864436
1 2020-09-24 00:12:00 0.400157 0.653619
2 2020-09-24 00:24:00 0.978738 0.864436
3 2020-09-24 00:36:00 2.240893 0.864436
4 2020-09-24 00:48:00 1.867558 2.269755
5 2020-09-24 01:00:00 0.153690 0.757559
6 2020-09-24 01:12:00 0.950088 0.045759
7 2020-09-24 01:24:00 -0.151357 -0.187184
8 2020-09-24 01:36:00 -0.103219 1.532779
9 2020-09-24 01:48:00 0.410599 1.469359
10 2020-09-24 02:00:00 0.144044 0.154947
11 2020-09-24 02:12:00 1.454274 0.378163
12 2020-09-24 02:24:00 0.761038 0.154947
13 2020-09-24 02:36:00 0.121675 0.154947
14 2020-09-24 02:48:00 0.443863 -0.347912
15 2020-09-24 03:00:00 0.333674 0.156349
16 2020-09-24 03:12:00 1.494079 1.230291
17 2020-09-24 03:24:00 -0.205158 1.202380
18 2020-09-24 03:36:00 0.313068 -0.387327
19 2020-09-24 03:48:00 0.323371 -0.302303
Solution 3:
Using what you've done, I'd do this:
df.Val = df.Val.fillna(df.Hour.map(df_val.squeeze()))
df.Dist = df.Val.fillna(df.Hour.map(df_dist.squeeze()))
Solution 4:
You can define a function for the required task:
def impute_nan(df,var,median):
df['new_'+var] = df[var].fillna(median)
median = df.Val.medain()
median
impute_nan(df,'Val',median)
this will give you a new coln named 'new_Val' with replaced NAN values.
Post a Comment for "Replace NaN Value With A Median?"