如何使用Pandas创建随机整数的DataFrame? [英] How to create a DataFrame of random integers with Pandas?

查看:3520
本文介绍了如何使用Pandas创建随机整数的DataFrame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果我使用 randn

I know that if I use randn,

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))

给我想要的东西,但带有正态分布的元素.但是,如果我只想要随机整数怎么办?

gives me what I am looking for, but with elements from a normal distribution. But what if I just wanted random integers?

randint通过提供范围来工作,但不能像randn那样提供数组.那么我该如何使用某个范围之间的随机整数呢?

randint works by providing a range, but not an array like randn does. So how do I do this with random integers between some range?

推荐答案

numpy.random.randint 接受第三个参数(size),您可以在其中指定输出数组的大小.您可以使用它来创建您的DataFrame-

numpy.random.randint accepts a third argument (size) , in which you can specify the size of the output array. You can use this to create your DataFrame -

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

在这里-np.random.randint(0,100,size=(100, 4))-创建大小为(100,4)的输出数组,并在[0,100)之间插入随机整数元素.

Here - np.random.randint(0,100,size=(100, 4)) - creates an output array of size (100,4) with random integer elements between [0,100) .

演示-

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

产生:

     A   B   C   D
0   45  88  44  92
1   62  34   2  86
2   85  65  11  31
3   74  43  42  56
4   90  38  34  93
5    0  94  45  10
6   58  23  23  60
..  ..  ..  ..  ..

这篇关于如何使用Pandas创建随机整数的DataFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆