创建数组
由python列表或元组创建数组
import numpy as np
a=np.array([2,3,4])
b=np.array([1.2,3.5,5.1])
创建2维数组
b = np.array([(1.5,2,3), (4,5,6)])
显式指定数组类型
c = np.array( [ [1,2], [3,4] ], dtype=complex )
通过函数创建ndarray
通过zeros或ones函数创建全0或全1的数组
np.zeros( (3,4) )
np.ones( (2,3,4), dtype=np.int16 )
通过empty函数创建没有任何具体值的数组
np.empty( (2,3) )
通过随机函数创建数组
from numpy.random import randn
import numpy as np
data = randn(2, 3)
通过数字序列创建ndarray
arange是Python内置函数range数组版
>>> np.arange( 10, 30, 5 )
array([10, 15, 20, 25])
>>> np.arange( 0, 2, 0.3 )
array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
如果没有特别指定,数组类型基本都是float64(浮点数)
通过linspace指定数字序列中元素个数
>>> from numpy import pi
>>> np.linspace( 0, 2, 9 ) # 9 numbers from 0 to 2
array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
>>> x = np.linspace( 0, 2*pi, 100 ) # useful to evaluate function at lots of points
>>> f = np.sin(x)
ndarray数据类型
查看数据类型
arr1 = np.array([1, 2, 3], dtype=np.float64)
arr2 = np.array([1, 2, 3], dtype=np.int32)
arr1.dtype
arr2.dtype
可以通过ndarray的astype方法显式的转换数据类型
arr = np.array([1, 2, 3, 4, 5])
arr.dtype
float_arr = arr.astype(np.float64)
float_arr.dtype
将浮点数转换为整数
arr = np.array([3.7, -1.2, -2.6, 0.5, 12.9, 10.1])
arr
arr.astype(np.int32)
将字符串转换为数值
numeric_strings = np.array(['1.25', '-9.6', '42'], dtype=np.string_)
numeric_strings.astype(float)
将Int转换为float
int_array = np.arange(10)
calibers = np.array([.22, .270, .357, .380, .44, .50], dtype=np.float64)
int_array.astype(calibers.dtype)
ndarray信息
ndarray中所有元素必须类型相同,每个数组都可以通过shape和dtype查看数组信息
查看数组各维度大小
ndarray.shape
数组中元素类型
ndarray.dtype
获取数组的维度数目
ndarray.ndim
数组元素的总数
ndarray.size
数组中每个元素的字节大小
ndarray.itemsize
打印数组
当打印数组时,Numpy以类似于嵌套列表的方式显示
一维数组打印
>>> a = np.arange(6) # 1d array
>>> print(a)
[0 1 2 3 4 5]
二维数组打印
>>> b = np.arange(12).reshape(4,3) # 2d array
>>> print(b)
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
三维数组打印
>>> c = np.arange(24).reshape(2,3,4) # 3d array
>>> print(c)
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]