【用jupyter notebook写的,所以格式和代码有些错位,需要的可以下载源文件】
下载链接:https://download.csdn.net/download/qq_38611819/11226068
import numpy as np
data2 = [[1, 2, 3, 4], [5, 6, 7]]
np.array(data2) # 如果list元素长度不等,python会将其统一作为list对象传入数组,作为统一类型的元素。
array([list([1, 2, 3, 4]), list([5, 6, 7])], dtype=object)
data=np.array([[[ 0.9526, -0.246 , -0.8856],
[ 0.6526, -0.646 , -0.7856],
[ 0.5639, 0.2379, 0.9104]],
[[ 0.9526, -0.246 , -0.8856],
[ 0.6526, -0.646 , -0.7856],
[ 0.5639, 0.2379, 0.9104]]])
print('shape:',data.shape)
print('dtype:',data.dtype)
shape: (2, 3, 3)
dtype: float64
函数 | 描述 |
---|---|
array | 转换输入数据(列表,数组或其它序列类型)到一个ndarray,可以推断一个dtype或明确的设置一个dtype。默认拷贝输入数据。 |
asarray | 转换输入为一个ndarray,当输入已经是一个ndarray时就不拷贝。 |
arange | 同内建的range函数,但不返回列表而是一个ndarray |
ones, ones_like | 根据提供的shape和dtype产生一个全1的数组。ones_like使用另一歌数组为入参,产生一个shape和dtype都相同的数组。 |
zeros, zeros_like | 同ones和ones_like,但是生成全0的数组 |
empty, enpty_like | 通过分配新内存来构造新的数组,但不同与ones 和 zeros,不初始任何值。 |
eye, identity | 生成一个NxN的单位方阵(对角线上为1,其它地方为0) |
假定 np.array 会返回一个全零的数组是不安全的。在许多情况下,如下所示,它将返回未初始化的垃圾值。
np.eye(5)
array([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
数据类型或dtype是一个特别的对象,保存了ndarray如何解释一块内存为特定类型数据的信息;Dtypes是使NumPy如此强大和灵活的一部分。在大多数情况下,它们直接映射到底层的机器表示,这是的很容易地读取和写入二进制流到磁盘上,也能链接低级语言,如C 或Fortran编写的代码。数值表示的dtypes以相同的方式命名:一个类型名,如 folt 或 int ,后面跟着一个表示数字有多少位的数字。一个标准的双精度浮点值(它是Python的 float 对象的底层表示)占据8字节或64位。因此,这一类型在NumPy中被认为是 float64 。见 表格4-2 是一个NumPy支持的全部数据类型的清单。
不要为了记忆NumPy的dtypes而烦恼,尤其你是一个新用户。通常只需要关心 你所处理数据的普通类型(浮点、复数、整形、布尔型、字符串或一般的Python对象)。 当你需要更多的控制数据如何存储到内存和磁盘,特别是大的数据集,知道你所控制的存储类型是很好的
类型 | 类型码 | 描述 |
---|---|---|
int8, uint8 | i1, u1 | 有符号和无符号8位(1字节)整数类型 |
int16, uint16 | i2, u2 | 有符号和无符号16位整数类型 |
int32, uint32 | i4, u4 | 有符号和无符号32位整数类型 |
int64, uint64 | i8, u8 | 有符号和无符号64位整数类型 |
float16 | f2 | 半精度浮点类型 |
float32 | f4 or f | 标准精度浮点。与C的 float 兼容 |
float64, float128 | f8 or d | 标准双精度浮点。与C的 double 和Python 的 folat 对象兼容 |
float128 | f16 or g | 扩展精度浮点 |
complex64, complex128, complex256 | c8, c16, c32 | 分别使用两个32,64,128位浮点表示的复数 |
bool | ? | 布尔值,存储 True 和 False |
object | O | Python对象类型 |
string_ | S | 定长字符串类型(每字符一字节)。例如,为了生成长度为10的字符串,使用 ‘S10’ |
unicode_ | f16 or g | 扩展精度浮点(字节书依赖平台)。同 string_ 有相同的语义规范(例如:U10 ) |
你可以使用ndarray的astype方法显示的把一个数组的dtype转换或 投射 到另外的类型:
In [31]: arr = np.array([1, 2, 3, 4, 5])
In [32]: arr.dtype
Out[32]: dtype('int64')
In [33]: float_arr = arr.astype(np.float64)
In [34]: float_arr.dtype
Out[34]: dtype('float64')
如果把浮点数转换到整形dtype,小数部分将会被截断;你可能有一个字符串数组表示的数字,也可以使用 astype 把它们转换到数字的形式;也可以使用速记的类型码字符串来指定一个dtype:
In [43]: empty_uint32 = np.empty(8, dtype='u4')
In [44]: empty_uint32
Out[44]:
array([ 0, 0, 65904672, 0, 64856792, 0,
39438163, 0], dtype=uint32)```
`调用 astype 总是会创建一个新的数组(原数据的拷贝),即使是新的dtype和原来的dtype相同。`
`值得牢记的是浮点数,如那些是 float64 和 float32 的数组,是唯一能够接近分数的。在复杂的计算中,可能会产生 浮点错误 ,计较时到了一定的小数位数时才有效。`
#### 1.1.3. 数组和纯量间的操作
数组非常重要,因为它们使你不使用循环就可以在数据上进行一系列操作。 这通常被叫做**矢量化**。相同大小的数组间的算术运算,其操作作用在对应的元素上;纯量的算术操作正如你期望的一样,把操作值作用于每一个元素.
`在不同大小的数组间的操作被叫做 broadcasting(广播) ,将在 第12章 详细讨论。深入的了解broadcasting在本书的多数地方是不必要的。`
#### 1.1.4. 基本的索引和切片
与列表的第一个重要的区别是 **数组的切片在原来的数组上(不生成新的数组)**。这意味着数据不会被拷贝,且对切片的任何修改都会影响源数组。*NumPy是设计用来处理大数据的情况,你可以想象如果NumPy坚持使用拷贝数据将会出现的性能和内存问题.*
`下面的操作是等价的:(原理不同,等价是因为索引为单独的整数)`
In [64]: arr2d[0][2] #切两次
Out[64]: 3
In [65]: arr2d[0, 2] #切一次
Out[65]: 3
**1.1.4带切片的索引**
```python
arr3=np.arange(32).reshape((8,4))
arr4=arr3.reshape(2,4,2,2)
arr4[1,3,1,1]
31
arr3[3:,1:3]# 不同于arr3[3:][1:3],后者中[1:3]为第二次切片索引。 #另,array([[[[5]]]]])的shape为(1,1,1,1)4维数组。
# arr3[3:][1:3]
array([[13, 14],
[17, 18],
[21, 22],
[25, 26],
[29, 30]])
1.1.5花式索引(Fancy索引)
花式索引指的是利用整数数组进行索引,花式索引跟切片不一样,它总是将数据复制到新数组中。
data2=np.arange(32).reshape((8, 4))
data2
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23],
[24, 25, 26, 27],
[28, 29, 30, 31]])
#要选出一个有特定顺序行(如:降序)的子集(list | tuple),可以传递一个列表或整形ndarray来指定顺序
data2[((3,6,5,5),)]
array([[12, 13, 14, 15],
[24, 25, 26, 27],
[20, 21, 22, 23],
[20, 21, 22, 23]])
data2[[3,5,6,1]][[3,0,3,1]] #[[3,0,2,1]]相当于在data2[[3,5,6,1]]上再次索引
array([[ 4, 5, 6, 7],
[12, 13, 14, 15],
[ 4, 5, 6, 7],
[20, 21, 22, 23]])
data2[[3,5,6,1],[3,0,2,1]] #与切片不同,此处花式索引使元素 (3, 3), (5, 0), (6, 2), 和(1, 1)被选择了
array([15, 20, 26, 5])
data2[[0,5,6,1]][:,[3,0,2,1]] #"[:,[3,0,2,1]]"中的冒号为第二次切片是选取[:]行,或者用np.ix_ 函数,也等效。
array([[ 3, 0, 2, 1],
[23, 20, 22, 21],
[27, 24, 26, 25],
[ 7, 4, 6, 5]])
data2[np.ix_([3,5,6,1],[3,0,2,1])] #等价于data2[[3,5,6,1]][:,[3,0,2,1]] 。
array([[15, 12, 14, 13],
[23, 20, 22, 21],
[27, 24, 26, 25],
[ 7, 4, 6, 5]])
1.1.6布尔索引
通过布尔索引从一个数组中选取数据,总是会创建数据的一份拷贝,即使是返回的数组没有改变。
names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
data = np.random.randn(7, 4)
data
array([[ 0.23903594, -0.35501341, -0.57009217, 0.77586805],
[ 0.67100508, -1.35272156, 0.73192961, 0.8847833 ],
[ 0.43465851, -1.4356666 , -0.2418999 , 1.26930254],
[-2.86548736, -0.03965445, -0.31672155, -0.88193036],
[-0.01093473, 0.32557902, -0.42078696, -1.56369328],
[ 0.91600953, -0.03003914, 0.26392468, -1.03476377],
[-0.37039468, 1.92939966, -0.27270669, -1.15385301]])
假设每一个名字都和 data 数组中的一行对应。如果我们想要选择与 ‘Bob’ 名字对应的所有行。象算术运算一样,数组的比较操作(例如 == )也可以矢量化。因此, names 和 Bob 字符串的比较会产生一个布尔数组:
names=='Bob'
array([ True, False, False, True, False, False, False])
当索引数组时可以传递这一布尔数组:
data[names == 'Bob']
array([[ 0.23903594, -0.35501341, -0.57009217, 0.77586805],
[-2.86548736, -0.03965445, -0.31672155, -0.88193036]])
布尔数组必须和它索引的坐标轴的长度相同。你甚至可以把布尔数组和切片或整数(或者整数序列,关于这一点后面会更多介绍)混合和匹配起来:
data[names == 'Bob', ::3][[1,0],[1,0]] #布尔索引、切片"::3"、花式索引"[[1,0],[1,0]]——(1,1)(0,0)被选中"
# data[names == 'Bob', ::3][[1,0]][[1,0]]
array([-0.88193036, 0.23903594])
为了选择除了 ‘Bob’ 之外的所有东西,你可以使用 != 或用 - 对条件表达式取反,还可以使用布尔算术操作符如 & (and) 和 | (or)来结合多个布尔条件。
In [96] mask = (names == 'Bob') | (names == 'Will')
In [97] data[mask]
为了设置 data 中所有的负值为0,我们只需要:
In [98] data[data < 0] = 0
使用一维布尔数组设置整行或列也非常简单
In [99] data[names != 'Joe'] = 7
备注:
项 import copy | 描述 |
---|---|
直接赋值 | 其实就是对象的引用(别名)。 |
浅拷贝(copy()) | 拷贝父对象,不会拷贝对象的内部的子对象(子对象改变,copy副本引用跟着变) |
深拷贝( copy.deepcopy()) | 完全拷贝父对象跟子对象 |
注意:Python的 and 和 or 关键字不能与布尔数组一起工作。(使用& | )
转置是一种特殊形式的变形,类似的它会返回基础数据的一个视窗,而不会拷贝任何东西。
数组有 transpose 方法和专门的 T 属性:
# np.dot 计算内部矩阵来计算矩阵内积:
In [114]:np.dot(arr.T, arr)
#对于更高维的数组, transpose 接受用于转置的坐标轴的号码的一个元组(for extra mind bending):
In [117]: arr.transpose((1, 0, 2))
#使用 .T 的转置,仅仅是交换坐标轴的一个特殊的情况;
#类似的 swapaxes 返回在数据上的一个视窗,而不进行拷贝:
In [119]: arr.swapaxes(1, 2)
ufunc:是一个在ndarrays的数据上进行基于元素的操作的函数。你可以认为它们是对简单函数的一个快速矢量化封装,它们接受一个或多个标量值并产生一个或多个标量值。
许多 ufunc 都是基于元素的简单变换,像 sqrt 或 exp ,这些都是一元/unary ufunc。另外一些,例如 add 或 maximum ,接受两个数组(因此,也叫二元/binary ufunc),并返回一个数组;虽然不常见,但有些ufunc的确可以返回多个数组。modf就是一个例子,它是Python内置函数的矢量化版本,用户浮点型数组的小数和整数部分:
arr=np.random.randn(7)*5
print(arr)
np.modf(arr)
# np.subtract(arr,0.5*arr)
[ 1.34156786 4.13932337 -0.59491365 -10.73272894 -2.61785531
-1.19913697 2.0253095 ]
(array([ 0.34156786, 0.13932337, -0.59491365, -0.73272894, -0.61785531,
-0.19913697, 0.0253095 ]),
array([ 1., 4., -0., -10., -2., -1., 2.]))
|
|
---|---|
abs, fabs | 计算基于元素的整数、浮点或复数的绝对值。对于没有复数的数据使用fabs更快 |
sqrt | 计算每个元素的平方根。等价于 arr ** 0.5 |
square | 计算每个元素的平方。等价于 arr ** 2 |
exp | 计算每个元素以e为底的指数。 |
log, log10, log2, log1p | 分别为自然对数(底数e)、10为底的log、2为底的log、log(1 + x) |
sign | 计算每个元素的符号:1(正数),0(零), -1(负数) |
ceil | 计算每个元素的ceiling值,即大于或等于该元素的最小整数 |
floor | 计算每个元素的floor值,即小于或等于该元素的最大整数 |
rint | 将各元素四舍五入到最近的整数,保留dtype |
modf | 将数组的小数和整数部分的以两个独立数组返回 |
isnan | 返回哪些元素是 NaN (不是一个数)的布尔型数组 |
isfinite, isinf | 分别返回一个表示“哪些元素是有穷的(非inf,非NaN)”、“哪些元素是无穷的”的布尔型数组 |
cos, cosh, sin sinh, tan, tanh | 普通型(regular) 和 双曲型(hyperbolic) 三角函数 |
arccos, arccosh, arcsin, arcsinh, arctan, arctanh | 反三角函数 |
logical_not | 计算各元素的not x的真值。等价于 -arr |
|
|
---|---|
add | 在数组中添加相应的元素 |
substract | 在第一个数组中减去第二个数组 |
multiply | 对数组元素相乘 |
divide, floor_divide | 除法、地板除(向下圆整除法,即去掉余数) |
power | 对第一个数组的元素A,第二个数组相应元素B执行A的B次幂 |
maximum, fmax | 基于元素的最大值。 fmax 忽略 NaN |
minimum, fmin | 基于元素的最小值。 fmin 忽略 NaN |
mod | 元素级求模(取余) |
copysign | 拷贝第二个参数的符号到第一个参数 |
greater, greater_equal, less, less_equal, not_equal | 基于元素的比较,产生布尔数组。等价于中缀操作符 >, >=, <, <=, ==, != |
logical_and, logical_or, logical_xor | 执行元素级的真值逻辑运算。等价于中缀操作符 & | ^ |
用数组表达式代替循环的做法,通常称为矢量化,且相比循环通常快上一两个数量级,甚至更多。
例:网格上计算sqrt(x2+y2),又或是,使用Meshgrid函数:
# import numpy as np
import matplotlib.pyplot as plt
x = np.array([0, 1, 2])
y = np.array([0, 1])
X, Y = np.meshgrid(x, y)
# print(X)
# print(Y)
r'''注意坐标矩阵中,其实有大量的重复——X XX的每一行都一样,Y YY的每一列都一样。
基于这种强烈的规律性,numpy提供的numpy.meshgrid()函数可以让我们快速生成坐标矩阵X XX,Y YY。'''
plt.plot(X, Y,
color='red', # 全部点设置为红色
marker='.', # 点的形状为圆点
linestyle='') # 线型为空,也即点与点之间不用线连接
plt.grid(True)
plt.show()
例,numpy.where函数是三元表达式x if condition else y的矢量化版本。
# 假设我们有一个布尔数组和两个值数组:
xarr=np.arange(1.1,1.6,0.1)
yarr=np.arange(2.1,2.6,0.1)
cond=np.array([True,False,True,True,False])
# 我们想要根据cond选取xarr、yarr的值
# 列表生成式写法:
result = [(x if c else y) for x,y,c in zip(xarr,yarr,cond)] #纯Python完成,速度不是很快;无法用于多维数组
print('列表生成式写法:\n',result)
# 使用numpy.where:
result=np.where(cond,xarr,yarr)
print('numpy.where写法:\n',result)
列表生成式写法:
[1.1, 2.2, 1.3000000000000003, 1.4000000000000004, 2.5000000000000004]
numpy.where写法:
[1.1 2.2 1.3 1.4 2.5]
numpy.where的第二和第三个参数不必是数组,它们可以是标量值。
arr=np.random.randn(4,4)
print(arr)
np.where(arr>0,2,-2)
# np.where(arr>0,2,arr)
# 【类似地,可以灵活的嵌套使用】
cond1=arr<0.2
cond2=arr>.6
# np.where(cond1&cond2,0,np.where(cond1,1,np.where(cond2,2,np.where(cond2==0,3,4)))) #注意书写格式:
np.where(cond1&cond2,0,
np.where(cond1,1,
np.where(cond2,2,
np.where(cond2==0,3,4))))
[[-1.7306949 0.06179629 0.18698957 -0.22064595]
[ 0.72079433 0.91743626 -1.05953871 2.49367922]
[ 0.37828736 2.01903097 0.11584296 0.05164432]
[ 0.8092589 0.45556406 -2.60004092 -0.61945267]]
array([[1, 1, 1, 1],
[2, 2, 1, 2],
[3, 2, 1, 1],
[2, 3, 1, 1]])
可以通过数组上的一组数学函数对整个数组或某个轴向的数据进行统计计算。sum、mean以及标准差std等聚合计算(aggregation,通常叫做简约(reduction))既可以当做数组的实例方法调用,也可以当作顶级numpy函数使用:
arr=np.arange(20).reshape(2,5,2)
arr.mean()
np.mean(arr)
arr.sum()
arr
array([[[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9]],
[[10, 11],
[12, 13],
[14, 15],
[16, 17],
[18, 19]]])
#【mean、sum这类函数还可以接受一个axis参数(用于计算该轴向上的统计值),最终结果是一个少一维的数组】
arr.mean(axis=0)
array([[ 5., 6.],
[ 7., 8.],
[ 9., 10.],
[11., 12.],
[13., 14.]])
另外,记住,Pandas保持了Numpy对关键字axis的用法,用法在Numpy库的词汇表当中有过解释:
轴用来为超过一维的数组定义的属性,二维数据拥有两个轴:第0轴沿着行的垂直往下,第1轴沿着列的方向水平延伸。
# 【其他如cumsum和cumprod之类的方法则不聚会,而是产生一个由中间结果组成的数组:】
arr=np.arange(9).reshape(3,3)
print(arr)
arr.cumsum(0) # 1即axis=1,若arr.cumsum()则依序计算,返回一维数组,类似和sum一样,无axis参数时对全部元素计算
# arr.cumprod(0)
[[0 1 2]
[3 4 5]
[6 7 8]]
array([[ 0, 1, 2],
[ 3, 5, 7],
[ 9, 12, 15]], dtype=int32)
基本数组统计方法(常用): 表4-5
方法 | 说明 |
---|---|
sum | 对数组中全部或某轴向的元素求和。零长度的数组的sum为0 |
mean | 算术平均数。零长度的数组的mean为NaN |
std、var | 分别为标准差和方差,自由度可调(默认为n) |
min、max | 最小值和最大值 |
argmin、argmax | 最小值和最大值的索引 |
cumsum | 所有元素累计和(返回中间结果组成的数组) |
cumprod | 所有元素的累计积(返回中间结果组成的数组) |
表4-5中的方法中,布尔值被强制转化为1和0。因此,sum常用于求True的个数:
#numpy.random.randn(d0, d1, …, dn)是从标准正态分布中返回一个或多个样本值。
#numpy.random.rand(d0, d1, …, dn)的随机样本位于[0, 1)中
arr=np.random.randn(4,5)
(arr>0).sum()
sum(arr<0)
array([1, 2, 2, 2, 3])
另外,any用于测试数组是否存在一个或多个True,all用于测试是否全是True
>>>(arr>0).all()
arr=np.random.randn(1,3)
# print(arr)
# np.sort(arr)
arr.sort(axis=0) # axis和sum等一样,若不传参则对全部元素排序
arr
array([[ 1.4701506 , 0.70363664, -0.03364976]])
顶级方法np.sort返回的是数组的已排序副本,就地排序则修改数组本身。
另外:
针对ndarray的基本集合运算中,最常用的可能就是np.unique了。
表4-6:数组的集合运算
方法 | 描述 |
---|---|
unique(x) | 计算x中的唯一元素,并返回有序结果 |
intersect1d(x,y) | 计算x和y中的公共元素,并返回有序结果 |
union1d(x,y) | 计算x和y的并集,并返回有序结果 |
in1d(x,y) | 得到一个表示“x的元素是否包含于y”的布尔型数组 |
setdiff1d(x,y)) | 集合的差,即元素在x中且不在y中 |
settxor1d(x,y) | 集合的对称差,即存在于一个数组中但不同时存在两个数组中的元素(简单点说就是“异或”) |
np.save和np.load是读写磁盘数据的两个主要函数。默认情况下数组以原始二进制格式保存在.npy文件中。
关于存取文本文件,主要使用pandas的read_csv和read_table函数。有时也用np.loadtxt或np.genfrontxt加载数据到numpy数组中。
线性代数是任何数组库的重要组成部分。
numpy提供用于矩阵乘法的dot函数(既是方法也是函数)。
numpy.linalg中有一组标准的矩阵分解运算以及诸如求逆和行列式之类的东西。
numpy.random模块对python内置random进行了补充。np.random 和 random 参数等方面自然不同。
表4-8:部分numpy.random函数
函数 | 说明 |
---|---|
seed | 确定随机数生成器的种子 |
premutation | 返回一个序列的随机排列或返回一个随机排列的范围 |
shuffle | 对一个序列就地随机排列 |
rand | 产生均匀分布的样本值,0到1之间 |
randint | 从给定上下限范围随机选取整数**(在python内置random中左闭右闭,而np.random中是左闭右开)** |
randn | 产生正态分布(平均值0,标准差1)的样本值,类似于MATLAB接口 |
binomial | 产生二项分布的样本值 |
normal | 产生正态(高斯)分布样本值 |
beta | 产生Beta分布样本值 |
chisquare | 产生卡方分布的样本值 |
gamma | 产生Gamma分布样本值 |
uniform | 产生在`[0,1)中均有分布的样本值 |
# 范例:随机漫步
# 循环写法
import random # 这是python内置模块
position=0
walk=[position]
steps=100
for i in range(steps):
step=1 if random.randint(0,1) else -1 # 内置random的randint接受2个参数,左闭右闭
position+=step
walk.append(position)
# print(walk)
# 数组写法 #使用np
nsteps=100
draws=np.random.randint(0,2,size=nsteps) # np的random中,randint接受4个参数,左闭右开
steps=np.where(draws==1,1,-1)
walk=steps.cumsum()
# print(walk)
如果你希望模拟多个随机漫步过程(比如500个),只需对上面的代码做一点点修改即可。
File "", line 1
如果你希望模拟多个随机漫步过程(比如500个),只需对上面的代码做一点点修改即可。
^
SyntaxError: invalid character in identifier
nwalks=500 # 500次随机漫步,“1行”1次。
nsteps=100
draws=np.random.randint(0,2,size=(nwalks,nsteps)) #相比上面只是size传入了二元元祖
steps=np.where(draws==1,1,-1)
walks=steps.cumsum(1) #横向加,一行漫步一次
print(walks)
[[-1 0 -1 ... -4 -3 -4]
[-1 0 -1 ... -8 -9 -8]
[-1 -2 -3 ... 4 5 4]
...
[ 1 0 1 ... 0 1 2]
[-1 0 -1 ... 24 23 22]
[-1 -2 -3 ... -2 -1 0]]
# np.random.randint(0,2,size=(5,3,2,1))
help(np.random.randint)
Help on built-in function randint:
randint(...) method of mtrand.RandomState instance
randint(low, high=None, size=None, dtype='l')
Return random integers from `low` (inclusive) to `high` (exclusive).
Return random integers from the "discrete uniform" distribution of
the specified dtype in the "half-open" interval [`low`, `high`). If
`high` is None (the default), then results are from [0, `low`).
Parameters
----------
low : int
Lowest (signed) integer to be drawn from the distribution (unless
``high=None``, in which case this parameter is one above the
*highest* such integer).
high : int, optional
If provided, one above the largest (signed) integer to be drawn
from the distribution (see above for behavior if ``high=None``).
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
dtype : dtype, optional
Desired dtype of the result. All dtypes are determined by their
name, i.e., 'int64', 'int', etc, so byteorder is not available
and a specific precision may have different C types depending
on the platform. The default value is 'np.int'.
.. versionadded:: 1.11.0
Returns
-------
out : int or ndarray of ints
`size`-shaped array of random integers from the appropriate
distribution, or a single such random int if `size` not provided.
See Also
--------
random.random_integers : similar to `randint`, only for the closed
interval [`low`, `high`], and 1 is the lowest value if `high` is
omitted. In particular, this other one is the one to use to generate
uniformly distributed discrete non-integers.
Examples
--------
>>> np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
>>> np.random.randint(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Generate a 2 x 4 array of ints between 0 and 4, inclusive:
>>> np.random.randint(5, size=(2, 4))
array([[4, 0, 2, 1],
[3, 2, 2, 0]])