Use random value in range to change value in dataset

Viewed 150

I have a dataset that is full of NaN and outliner values.

I have managed to locate and replace this values by random number from certain range using:

dataset.loc[(dataset['MaxHR'] == 1000) & (dataset['Age'] < 50), 'MaxHR'] = random.randrange(138, 176)

My problem is that I meant that random.randrange(138, 176) pick one number for each time that number 1000 occur.

My code just picks a number and for every row and column that meet conditions assert one number for the whole column.

1 Answers

You can consider to use the applymap method. Here a simple example :

df = pd.DataFrame([[0, 1], [1, 2], [1, 3]], columns=['a', 'b'])
def clean(x):
    if x == 1:
        return random.randrange(138, 176)
    else:
        return x

df = df.applymap(lambda x: clean(x))
Related