Stu*_*ent 3 python random numpy pandas
目标:为构造字段“出生”内的每一行创建一个唯一且随机的数字。
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
Run Code Online (Sandbox Code Playgroud)
上面的代码为所有行生成一个随机数,如下所示:
A B Birth
0 1 4 1974
1 2 5 1974
2 3 6 1974
Run Code Online (Sandbox Code Playgroud)
相反,我对以下内容感兴趣:
A B Birth
0 1 4 1904
1 2 5 1978
2 3 6 1934
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激。
使用numpy
import numpy as np
df['Birth'] = np.random.randint(1905,1995, len(df))
Run Code Online (Sandbox Code Playgroud)