Skip to content

Pickle Problem


Given a Series called pickle, replace NaNs using the following algorithm.

for each NaN:
  get the nearest non NaN value before and after it
  if both of those values exist:
    replace NaN with the minimum of those two non NaN values
  else:
    replace NaN with the nearest non NaN value
import numpy as np
import pandas as pd

pickle = pd.Series([1.5, np.nan, 2.3, np.nan, np.nan, -3.9, np.nan, 4.5, np.nan, np.nan, np.nan, 1.9, np.nan])

print(pickle)
# 0     1.5
# 1     NaN
# 2     2.3
# 3     NaN
# 4     NaN
# 5    -3.9
# 6     NaN
# 7     4.5
# 8     NaN
# 9     NaN
# 10    NaN
# 11    1.9
# 12    NaN
# dtype: float64

Try with Google Colab