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
How to create a DataFrame of random integers with Pandas?
提问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?
给了我我正在寻找的东西,但元素来自正态分布。但是如果我只想要随机整数呢?
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?
randint
通过提供范围而不是数组来randn
工作。那么我如何使用某个范围之间的随机整数来做到这一点呢?
采纳答案by Anand S Kumar
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
-
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
.. .. .. .. ..