1.定义
NumPy 是一个 Python 包。 它代表 “Numeric Python”。 它是一个由多维数组对象和用于处理数组的例程集合组成的库。
NumPy的数组类被称作ndarray。通常被称作数组。
2.初始化
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
-
object 任何暴露数组接口方法在这里插入代码片的对象都会返回一个数组或任何(嵌套)序列。
-
dtype 数组的所需数据类型,可选。
-
bool_ 存储为一个字节的布尔值(真或假)
-
int_ 默认整数,相当于 C 的long,通常为int32或int64
-
intc 相当于 C 的int,通常为int32或int64
-
intp 用于索引的整数,相当于 C 的size_t,通常为int32或int64
-
int8 字节(-128 ~ 127)
-
int16 16 位整数(-32768 ~ 32767)
-
int32 32 位整数(-2147483648 ~ 2147483647)
-
int64 64 位整数(-9223372036854775808 ~ 9223372036854775807)
-
uint8 8 位无符号整数(0 ~ 255)
-
uint16 16 位无符号整数(0 ~ 65535)
-
uint32 32 位无符号整数(0 ~ 4294967295)
-
uint64 64 位无符号整数(0 ~ 18446744073709551615)
-
float_ float64的简写
-
float16 半精度浮点:符号位,5 位指数,10 位尾数
-
float32 单精度浮点:符号位,8 位指数,23 位尾数
-
float64 双精度浮点:符号位,11 位指数,52 位尾数
-
complex_ complex128的简写
-
complex64 复数,由两个 32 位浮点表示(实部和虚部)
-
complex128 复数,由两个 64 位浮点表示(实部和虚部)
3.数组属性
3.1 ndarray.shape
这一数组属性返回一个包含数组维度的元组,它也可以用于调整数组大小。
这会调整数组大小
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
a.shape = (3,2) #维度不会改变
print(a)
3.2ndarray.ndim
这一数组属性返回数组的维数。
numpy.reshape(arr, newshape, order')
code
a=np.array([[1,2],[3,4]])
a.ndim #2
a=array([[1, 2, 3, 4]])
a.ndim #2
b=a.reshape(1,4,1)
b.ndim#3
b=a.reshape(1,4)
b.ndim#2
b=a.reshape(4)
b.ndim#1
a=np.array([1,2])
a.ndim #1
d.max(axis=0) #轴的方向
3.4 ndarray.flatten(order)
该函数返回折叠为一维的数组副本,函数接受下列参数:
3.5 numpy.ravel
这个函数返回展开的一维数组,并且按需生成副本。返回的数组和输入数组拥有相同数据类型。这个函数接受两个参数。
numpy.ravel(a, order)
#order:'C' -- 按行,'F' -- 按列,'A' -- 原顺序,'k' -- 元素在内存中的出现顺序。
code
c = [[1, 2], [3, 4]] # 二维列表
d = np.array(c) # 二维numpy数组
d.shape # (2, 2)
d.size # 4
d.max(axis=0) # 找维度0,也就是最后一个维度上(列方向)的最大值,array([3, 4])
d.mean(axis=0) # 找维度0,也就是第一个维度上的均值,array([ 2., 3.])
d.flatten() # 展开一个numpy数组为1维数组,array([1, 2, 3, 4])
np.ravel(c) # 展开一个可以解析的结构为1维数组,array([1, 2, 3, 4])
3.6 numpy.transpose(arr, axes)
这个函数翻转给定数组的维度。如果可能的话它会返回一个视图。函数接受下列参数:
import numpy as np
a = np.arange(12).reshape(3,4)
print( '原数组:' )
print (a)
print ('\n')
print ('转置数组:' )
print (np.transpose(a))
a.T#该函数属于ndarray类,
4 数组创建
numpy.zeros(shape, dtype = float, order = 'C')
numpy.ones(shape, dtype = None, order = 'C')
4.1 生成数值范围的数组
numpy.arange(start, stop, step, dtype)
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
endpoint 序列中是否包含stop值,默认为ture
logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None):
start 起始值是base ** start
stop 终止值是base ** stop
4.3 切片和索引
c = [[1, 2], [3, 4],[5,6]] # 二维列表
d = np.array(c) # 二维numpy数组
d[...,0] #输出第一列
d[:,0]
d[0][1] #输出特定位置
d[1:3,1]
4.4 数组加和乘
a = np.array([1,2,3,4])
b = np.array([10,20,30,40])
c = a * b
a = np.array([[0.0,0.0,0.0],[10.0,10.0,10.0],[20.0,20.0,20.0],[30.0,30.0,30.0]])
b = np.array([1.0,2.0,3.0])
c=a+b
https://blog.csdn.net/a373595475/article/details/79580734
http://blog.chinaunix.net/uid-21633169-id-4408596.html
http://python.jobbole.com/87471/