Search code examples
pythonpandasrandomfillna

Replace NaN with random number


I have a dataframe of numbers such as:

A           B
2019-10-31  0.035333
2019-10-31  NaN
2019-11-30  -0.108532
2019-11-30  -0.030604
2019-11-30  NaN

I want to replace the NaN's in column B with a random gaussian number:

from random import seed
from random import gauss
# seed random number generator
seed(1)
# generate some Gaussian value
value = gauss(0, 0.1)

However, if I use the following code:

df.fillna(gauss(0, 0.1))

It fills all missing values with the same random value while I want a new random value for each NaN. How should I acchieve this?


Solution

  • Python pandas suggests replace function.

    df.replace('NaN', gauss(1, 0.1))
    

    Output:

                A         B
    0  2019-10-31  0.035330
    1  2019-10-31 -0.036289
    2  2019-11-30 -0.108532
    3  2019-11-30 -0.030604
    4  2019-11-30 -0.036289