NumPy数组操作与通用函数全解析
1. NumPy标准数据类型
NumPy数组中的值是单一类型的,了解这些类型及其限制非常重要。由于NumPy是用C语言构建的,这些类型对于C、Fortran等相关语言的用户来说会很熟悉。
1.1 创建特殊数组
可以使用以下代码创建特殊数组:
import numpy as np
# Create a 3x3 identity matrix
np.eye(3)
# 输出
# array([[ 1., 0., 0.],
# [ 0., 1., 0.],
# [ 0., 0., 1.]])
# Create an uninitialized array of three integers
# The values will be whatever happens to already exist at that
# memory location
np.empty(3)
# 输出
# array([ 1., 1., 1.])
1.2 指定数据类型
在构造数组时,可以使用字符串或关联的NumPy对象来指定数据类型,示例如下:
np.zeros(10, dtype='int16')
np.zeros(10, dtype=np.int16)