Masking each DataFrame Column using random.randint()

Viewed 119

i got curious as a beginner and a student about the python masking, so i made this code:

import numpy as np
import pandas as pd
import random

A = [123, 321, 213]
B = [456, 546, 654]
C = [789, 987, 879]

lst = {
    "A":A,
    "B":B,
    "C":C}

df = pd.DataFrame(lst)

the code above produces this:

A   B   C

0 123 456 789

1 321 546 987

2 213 654 879

and i made this code to mask the column:

df['A'].mask(df['A']>1, np.random.randint(1,3))

which now turns the values of column A into:

0 1

1 1

2 1

but i want a desired output to be like this:

0 2

1 3

2 1

any chance that it can be possible?, if so can you give me pointers?

1 Answers
df['A'].apply(lambda x: np.random.randint(1,4) if x > 1 else 0)

It's a random result so you may not get [2,3,1] in the first try. If you want this only and not random then you have to change seeds and find this.

Luckily I found for you,

np.random.seed(90)
df['A'].apply(lambda x: np.random.randint(1,4) if x > 1 else 0)

0    2
1    3
2    1
Name: A, dtype: int64

Related