Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python how do I generate a random number within a range for each row in Pandas dataframe?

Objective: to create a unique and random number for each row within the constructed field 'Birth'.

import pandas as pd
import numpy as np

df1=pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])])
df1['Birth']= random.randrange(1905,1995, len(df1))
df1

The above code produces a single random number for all rows as follows:

    A   B   Birth
0   1   4   1974
1   2   5   1974
2   3   6   1974

I am instead interested in the following:

    A   B   Birth
0   1   4   1904
1   2   5   1978
2   3   6   1934

Any help would be appreciated.

like image 953
Student Avatar asked Dec 17 '25 20:12

Student


1 Answers

Using numpy

import numpy as np
df['Birth'] = np.random.randint(1905,1995, len(df))
like image 52
hellpanderr Avatar answered Dec 20 '25 09:12

hellpanderr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!