Python 如何使用 Pandas 创建随机整数的 DataFrame?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32752292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:11:05  来源:igfitidea点击:

How to create a DataFrame of random integers with Pandas?

pythonpandasdataframesizeshapes

提问by AlanH

I know that if I use randn,

我知道,如果我使用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?

给了我我正在寻找的东西,但元素来自正态分布。但是如果我只想要随机整数呢?

randintworks by providing a range, but not an array like randndoes. So how do I do this with random integers between some range?

randint通过提供范围而不是数组来randn工作。那么我如何使用某个范围之间的随机整数来做到这一点呢?

采纳答案by Anand S Kumar

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

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

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

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

这里 - np.random.randint(0,100,size=(100, 4))- 创建一个大小为 的输出数组,(100,4)其中包含介于 之间的随机整数元素[0,100)



Demo -

演示 -

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

which produces:

它产生:

     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
..  ..  ..  ..  ..