python - 使用 np.random 生成值

标签 python numpy pandas

我尝试向 df 添加新列,其中所有值都为 0 或 1。 我用

df['name'] = np.random.randint(0, 1)

但它返回所有 0 的列。

最佳答案

使用形状说明符让它在区间 [0,2) 中创建一个随机整数数组,即 01长度与 dataframe 中的行数相同,np.random.randint(0, 2,(df.shape[0])) 然后指定为新专栏。因此,实现将是 -

df['name'] = np.random.randint(0, 2,(df.shape[0]))

关于python - 使用 np.random 生成值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38184886/

相关文章:

python - 使用 Python 将电子邮件的主题和正文提取到字典中

Python 3.6 - 'NoneType' 测试失败

python - 加快正态分布概率质量分配

python - numpy 将数组元素与另一个数组相乘

python - 在Python中连接多列上的两个数据框

python - 使用 python 添加取决于 2 df 的列

python exe文件在Windows xp上启动时崩溃

python - Gitlab CI : Failed building wheel for opencv-python

python - 如何在一个 NumPy 数组中搜索位置,以便在这些位置获取第二个 NumPy 数组中的值?

python - 将多个 json 数据添加到 Pandas 数据帧