pandas change column value based on other column

Viewed 122

I am trying to change [age] values with random number in the range defined in [tranches_age] column

index age tranches_age
1 NaN 80-85
2 NaN 70-75
3 NaN 30-35

enter image description here

3 Answers

Use apply

df = pd.DataFrame([
    [1, None, '80-85'], 
    [2, None, '70-75'], 
    [3, None, '30-35']], 
    columns=['index', 'age', 'tranches_age']
)


def transform(x):
    agemin, agemax = map(int, x.split('-'))
    return random.randint(agemin, agemax)

df['age'] = df['tranches_age'].apply(transform)

Should output things like

   index  age tranches_age
0      1   85        80-85
1      2   71        70-75
2      3   35        30-35

etc.

Compute min and width of the range and then generate random number using (min + width*np.random.random()). We can vectorize these operations and hence probably better performance.

Use:

min_r = df.tranches_age.str[:2].astype(int)
widths = df.tranches_age.str[3:].astype(int) - min_r
df['age'] = (min_r + widths* np.random.random(size=(widths.shape[0]))).astype(int)

Output:

>>> df
   index  age tranches_age
0      1   82        80-85
1      2   70        70-75
2      3   31        30-35

Try with numpy random.randint

df['new'] = df['tranches_age'].apply(lambda x : np.random.randint(low=x.split('-')[0],high=x.split('-')[1]))
0    83
1    72
2    32
Name: tranches_age, dtype: int64
Related