ndarray数组的操作
- 数组数据转换
- 数组形状变换
- 数组数据选择与操作
- 数组计算处理
- 数组算术运算
一、数组数据转换
数组数据转化方法 | 方法说明 |
---|---|
ndarray.item(*args) | Copy an element of an array to a standard Python scalar and return it. |
ndarray.tolist() | Return the array as a (possibly nested) list. |
ndarray.itemset(*args) | Insert scalar into an array (scalar is cast to array’s dtype, if possible) |
ndarray.tostring([order]) | Construct Python bytes containing the raw data bytes in the array. |
ndarray.tobytes([order]) | Construct Python bytes containing the raw data bytes in the array. |
ndarray.tofile(fid[, sep, format]) | Write array to a file as text or binary (default). |
ndarray.dump(file) | Dump a pickle of the array to the specified file. |
ndarray.dumps() | Returns the pickle of the array as a string. |
ndarray.astype(dtype[, order, casting, …]) | Copy of the array, cast to a specified type. |
ndarray.byteswap([inplace]) | Swap the bytes of the array elements |
ndarray.copy([order]) | Return a copy of the array. |
ndarray.view([dtype, type]) | New view of array with the same data. |
ndarray.getfield(dtype[, offset]) | Returns a field of the given array as a certain type. |
ndarray.setflags([write, align, uic]) | Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively. |
ndarray.fill(value) | Fill the array with a scalar value. |
注意:copy还读对应一个numpy函数:numpy.copy
import numpy as np
#定义一个矩阵
m = np.random.randint ( 10, size=(3, 4) ) #创建形状为3*4的随机矩阵,值 [ 0, 10 )。
print ( m )
[[2 2 2 3]
[7 9 3 9]
[8 7 4 1]]
1.item 以标量形式返回一个元素
b=np.array([1])
print ( b.item () ) #无参数情况,只对size=1的ndarray有效
print ( m.item ( 2 ) ) #先调用flat转换为1维,再取值
print ( m.item ( 0, 0 ) )
print ( m.item ( ( 2 ) ) ) #等价于m.item ( 2 )
# print ( m.item ( ( 1,1,1 ) ) ) #数组维数不能超过维度
1
3
5
3
2. itemset 设置标量值
m.itemset ( 1 , 11 )
m.itemset ( ( 2 ), 22 )
m.itemset ( ( 2 ,3 ), 33 )
print ( m )
[[ 5 11 22 8]
[ 5 8 3 9]
[ 9 0 2 33]]
3. tolist,tostring,tibytes,tofile 格式转换
#tolist调用
print ( m.tolist ( ) ) #tolist是没有参数的
#tostring调用
print ( m.tostring ( ) ) #tostring带一个order参数C格式或者Fortran格式,默认C(行优先)
print ( m.tostring ( 'C' ) )
print ( m.tostring ( 'F' ) )
#tobytes调用
print ( m.tobytes ( ) ) #与tostring功能一样
#tofile调用
m.tofile("m.txt",sep="@",format="%04d" ) #sep分隔符默认"",format格式化默认字符串输出,输出如下。
#0005@0011@0022@0008@0005@0008@0003@0009@0009@0000@0002@0033
#第一个参数可以是:文件名 与 一个打开的文件描述符对象。
#文件名的位置:如果不使用绝对位置,相对位置就是保存在ipynb文件作为相对位置。
[[5, 11, 22, 8], [5, 8, 3, 9], [9, 0, 2, 33]]
b'\x05\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00\x00\x00\x00\x00\x16\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00!\x00\x00\x00\x00\x00\x00\x00'
b'\x05\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00\x00\x00\x00\x00\x16\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00!\x00\x00\x00\x00\x00\x00\x00'
b'\x05\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00!\x00\x00\x00\x00\x00\x00\x00'
b'\x05\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00\x00\x00\x00\x00\x16\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00!\x00\x00\x00\x00\x00\x00\x00'
None
4. astype与copy返回克隆
#ndarray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True) 返回指定类型的克隆
# 详细的参考见官方文档
print ( m.astype( np.float32 ) )
#直接返回克隆:ndarray.copy(order='C') :order控制内存布局
print ( m.copy ( 'C' ) )
[[ 5. 11. 22. 8.]
[ 5. 8. 3. 9.]
[ 9. 0. 2. 33.]]
[[ 5 11 22 8]
[ 5 8 3 9]
[ 9 0 2 33]]
5. 数据视图view
print ( m.view ( dtype=np.float32) ) #numpy标量类型或者ndarray的子类型
print ( m.view ( type=np.ndarray) )
print ( m.view ( type=np.matrix) ) #子类型
[[7.0e-45 0.0e+00 1.5e-44 0.0e+00 3.1e-44 0.0e+00 1.1e-44 0.0e+00]
[7.0e-45 0.0e+00 1.1e-44 0.0e+00 4.2e-45 0.0e+00 1.3e-44 0.0e+00]
[1.3e-44 0.0e+00 0.0e+00 0.0e+00 2.8e-45 0.0e+00 4.6e-44 0.0e+00]]
[[ 5 11 22 8]
[ 5 8 3 9]
[ 9 0 2 33]]
[[ 5 11 22 8]
[ 5 8 3 9]
[ 9 0 2 33]]
6. 填充数据fill
#ndarray.fill(value)
m.fill ( 8 )
print ( m )
[[8 8 8 8]
[8 8 8 8]
[8 8 8 8]]
二、数组形状变换
数组形状操作方法 | 方法说明 |
---|---|
ndarray.reshape(shape[, order]) | Returns an array containing the same data with a new shape. |
ndarray.resize(new_shape[, refcheck]) | Change shape and size of array in-place. |
ndarray.transpose(*axes) | Returns a view of the array with axes transposed. |
ndarray.swapaxes(axis1, axis2) | Return a view of the array with axis1 and axis2 interchanged. |
ndarray.flatten([order]) | Return a copy of the array collapsed into one dimension. |
ndarray.ravel([order]) | Return a flattened array. |
ndarray.squeeze([axis]) | Remove single-dimensional entries from the shape of a. |
【注意】:如果其中只有一个元素的元组,可以直接使用整数表示,比如(1)可以直接用1替代。
除了transpose与flatten,都存在numpy对应的函数。
1. reshape与resize的比较
print ( m )
#print ( m.reshape ( ( 2, 5 ) ) ) #必须满足条件:旧形状的大小 = 新形状的大小
print ( m.reshape ( ( 5, 2 ) ) )
print ( m.resize ( ( 3, 3 ) ) ) #这个改变大小,没有返回值
print ( m )
[[8 8 8 8 8]
[8 8 8 8 8]]
[[8 8]
[8 8]
[8 8]
[8 8]
[8 8]]
None
[[8 8 8]
[8 8 8]
[8 8 8]]
2. transpose与swapaxes函数
m = np.random.randint ( 10, size=(3, 4) )
#ndarray.transpose(*axes)
print ( m )
print ( m.transpose ( ) ) #无参数
print ( m.transpose ( (1, 0 ) ) ) #元组参数(1个参数没有意义。因为对一维情况不会产生任何变化)
print ( m.transpose ( 0, 1 ) ) #n个整数参数 与元组一样
#解释下:transpose可以控制转置矩阵方式:(i,j) 元组的值i表述旧矩阵的维度,元组下标0表示新矩阵的维度
#(1,0)表示新矩阵的行(0:第一维)是旧矩阵的列(1:第二维)。
m = np.random.randint ( 10, size=(3, 4, 2 ) )
print("转换前:")
print(m)
print("转换后:")
print ( m.transpose ( 1, 2, 0 ) ) #就是坐标轴变换(新矩阵的D-0就是旧矩阵的D-1,新矩阵的D-1就是旧矩阵的D-2)
#ndarray.swapaxes(axis1, axis2) 两个维度互换
print ( m.swapaxes ( 0, 0 ) )
print ( m.swapaxes ( 1, 2 ) )
print ( m.transpose ( 0, 2, 1 ) ) #等价于 print ( m.swapaxes ( 1, 2 ) )
[[0 7 8 1]
[6 4 3 0]
[9 1 4 6]]
[[0 6 9]
[7 4 1]
[8 3 4]
[1 0 6]]
[[0 6 9]
[7 4 1]
[8 3 4]
[1 0 6]]
[[0 7 8 1]
[6 4 3 0]
[9 1 4 6]]
转换前:
[[[3 5]
[9 8]
[8 7]
[3 1]]
[[8 8]
[5 5]
[9 6]
[3 5]]
[[4 4]
[3 7]
[4 1]
[8 5]]]
转换后:
[[[3 8 4]
[5 8 4]]
[[9 5 3]
[8 5 7]]
[[8 9 4]
[7 6 1]]
[[3 3 8]
[1 5 5]]]
[[[3 5]
[9 8]
[8 7]
[3 1]]
[[8 8]
[5 5]
[9 6]
[3 5]]
[[4 4]
[3 7]
[4 1]
[8 5]]]
[[[3 9 8 3]
[5 8 7 1]]
[[8 5 9 3]
[8 5 6 5]]
[[4 3 4 8]
[4 7 1 5]]]
[[[3 9 8 3]
[5 8 7 1]]
[[8 5 9 3]
[8 5 6 5]]
[[4 3 4 8]
[4 7 1 5]]]
3. flatten、ravel与squeeze函数
#ndarray.flatten(order='C') 转换成 1 维
print ( m.flatten ( ) )
# ndarray.ravel([order]) 与flatten一样
print ( m.ravel ( ) )
#ndarray.squeeze(axis=None) 删除长度为axis的维度
m = np.random.randint ( 10, size=(3, 2, 1 ) )
print ( m.squeeze ( ) ) # 删除所有长度为1的维度
print ( m.shape)
print ( m.squeeze ( axis=2 ) ) #删除维度的长度为1的维度,如果多个维度的长度都为1,则指定维度,否则全删
[7 5 3 7 5 7]
[7 5 3 7 5 7]
[[4 3]
[0 6]
[1 6]]
(3, 2, 1)
[[4 3]
[0 6]
[1 6]]
三、数组数据选择与操作
数据选择与操作方法 | 方法说明 |
---|---|
ndarray.take(indices[, axis, out, mode]) | Return an array formed from the elements of a at the given indices. |
ndarray.put(indices, values[, mode]) | Set a.flat[n] = values[n] for all n in indices. |
ndarray.repeat(repeats[, axis]) | Repeat elements of an array. |
ndarray.choose(choices[, out, mode]) | Use an index array to construct a new array from a set of choices. |
ndarray.sort([axis, kind, order]) | Sort an array, in-place. |
ndarray.argsort([axis, kind, order]) | Returns the indices that would sort this array. |
ndarray.partition(kth[, axis, kind, order]) | Rearranges the elements in the array in such a way that value of the element in kth position is in the position it would be in a sorted array. |
ndarray.argpartition(kth[, axis, kind, order]) | Returns the indices that would partition this array. |
ndarray.searchsorted(v[, side, sorter]) | Find indices where elements of v should be inserted in a to maintain order. |
ndarray.nonzero() | Return the indices of the elements that are non-zero. |
ndarray.compress(condition[, axis, out]) | Return selected slices of this array along given axis. |
ndarray.diagonal([offset, axis1, axis2]) | Return specified diagonals. |
【注意】:如果axis为None,数组作为1-D数组处理。如果是整数,表示对应的维度
这些函数在numpy都存在对应函数。
1. put与take函数
m = np.random.randint ( 10, size=(3, 4) )
# ndarray.take(indices, axis=None, out=None, mode='raise')
# mode : {'raise', 'wrap', 'clip'}, optional
# mode=‘raise’,表示a中数必须在[0,n-1]范围内
# mode=‘wrap’,a中数可以是任意的整数(signed),对n取余映射到[0,n-1]范围内
# mode='clip',a中数可以是任意的整数(signed),负数映射为0,大于n-1的数映射为n-1
print ( m )
print ( m.take ( 1 ) )
print ( m.take ( ( 1 ,2 ) ) )
print ( m.take ( [ 1 ,2 ] ) ) #与上面一样
print ( m.take ( [ [1 ,2 ] ,[ 3,4] ] ) ) #按照一维的方式,返回参数索引格式的数据。
print ( m.take ( [ [1 ,2 ] ,[ 0,1] ] , axis=0) ) #axis=0 按照行,axis=None就是全部
[[8 3 5 4]
[1 8 2 0]
[8 4 3 7]]
3
[3 5]
[3 5]
[[3 5]
[4 1]]
[[[1 8 2 0]
[8 4 3 7]]
[[8 3 5 4]
[1 8 2 0]]]
#ndarray.put(indices, values, mode='raise')
#等价于a.flat[n] = values[n]
print ( m )
m.put( ( 1, 2, 3 ), ( 11, 12, 13, 14) ) #根据indices中对应下标,到values中取值,用来修改数组中对应位置的值
print ( m )
[[8 3 5 4]
[1 8 2 0]
[8 4 3 7]]
[[ 8 11 12 13]
[ 1 8 2 0]
[ 8 4 3 7]]
2.sort,argsort与searchsorted函数
m = np.random.randint ( 10, size=(3, 4) )
#ndarray.sort(axis=-1, kind='quicksort', order=None)
print ( m )
m.sort ( ) #默认按照axis=1排序(每行排序)
print ( m )
m.sort ( axis = 0 ) #按照axis = 0排序(每列排序)
print ( m )
[[2 1 6 2]
[9 7 8 7]
[9 9 5 3]]
[[1 2 2 6]
[7 7 8 9]
[3 5 9 9]]
[[1 2 2 6]
[3 5 8 9]
[7 7 9 9]]
m = np.random.randint ( 10, size=(3, 4) )
#ndarray.argsort(axis=-1, kind='quicksort', order=None) 返回排序的下标
print ( m )
print ( m.argsort ( ) ) #默认按照axis=1排序(每行排序)
print ( m )
print ( m.argsort ( axis = 0 ) ) #按照axis = 0排序(每列排序)
print ( m )
[[4 1 7 5]
[9 5 3 7]
[9 1 3 6]]
[[1 0 3 2]
[2 1 3 0]
[1 2 3 0]]
[[4 1 7 5]
[9 5 3 7]
[9 1 3 6]]
[[0 0 1 0]
[1 2 2 2]
[2 1 0 1]]
[[4 1 7 5]
[9 5 3 7]
[9 1 3 6]]
#ndarray.searchsorted(v, side='left', sorter=None) #找出v应该排序的位置
m = np.array ( [
[ 5, 3, 8, 4, 2 ],
[ 7, 1, 6, 9, 3 ],
[ 8, 2, 6, 3, 7]
] )
#print ( m.searchsorted ( 5 , sorter=m.argsort( ) ) ) # 只作用于1-D数组
m=np.array( [ 1,2,5,6,9] )
print ( m.searchsorted ( 8 ) ) #返回8在m数组排序应该在对的位置,只对有序作用
m=np.array( [ 2, 5, 4, 9, 7 ] )
print ( m.searchsorted ( 8 ) ) #对无序可以运行,意义不大
print ( m.searchsorted ( 8 , sorter=m.argsort( ) ) ) #添加一个排序器
4
5
4
3. repeat 函数
#ndarray.repeat(repeats, axis=None) #按照指定axis维度复制指定次数
m = np.array ( [
[ 5, 3, 8 ],
[ 7, 1, 6 ],
[ 8, 2, 6 ]
] )
print ( m.repeat ( 2 ) ) #复制2次,先flat,再复制
print ( m.repeat ( 2 ,axis = 0) ) #按照行复制2次
[5 5 3 3 8 8 7 7 1 1 6 6 8 8 2 2 6 6]
[[5 3 8]
[5 3 8]
[7 1 6]
[7 1 6]
[8 2 6]
[8 2 6]]
4. choose与nonzero函数
#ndarray.choose(choices, out=None, mode='raise') #把数组当做下标。从choices中取对应的值。
m = np.array ( [ #索引
[ 1, 2, 3 ],
[ 3, 2, 1 ],
[ 2, 2, 2 ]
] )
print ( m.choose ( [ -1, -2, -3, -4, -5 ] ) ) #被选的值
#mode的取值意义见上。
[[-2 -3 -4]
[-4 -3 -2]
[-3 -3 -3]]
# ndarray.nonzero() 返回非零元素的下标索引
m = np.array ( [
[ 1, 0, 3 ],
[ 3, 2, 0 ],
[ 2, 2, 0 ]
] )
print ( m )
print ( m.nonzero( ) ) #返回非零的下标。返回两个数组,一个按照行,一个按照列,行列对应形成非零的下标
[[1 0 3]
[3 2 0]
[2 2 0]]
(array([0, 0, 1, 1, 2, 2]), array([0, 2, 0, 1, 0, 1]))
5.compress函数
#ndarray.compress(condition, axis=None, out=None)
#返回按照axis维度的切片,条件是1-D布尔数组
m = np.array ( [
[ 1, 0, 3 ],
[ 4, 2, 0 ],
[ 2, 2, 0 ]
] )
print ( m.compress ( [True , True, False, True ] ) ) #按照条件返回元素axis=None,等于先flat再操作
print ( m.compress ( [True , False, True ], axis = 0 ) ) #按照条件返回行
[1 0 4]
[[1 0 3]
[2 2 0]]
6. diagonal函数
#ndarray.diagonal(offset=0, axis1=0, axis2=1) 按照坐标轴axis1与axis2返回对角线,返回的是1-D数组
m = np.array ( [
[ 1, 0, 3 ],
[ 4, 2, 0 ],
[ 2, 2, 0 ]
] )
print ( m.diagonal ( ) )
print ( m.diagonal (1 ) )
print ( m.diagonal (1, axis1 = 1, axis2 = 0) ) #下三角对角
[1 2 0]
[0 0]
[4 2]
7. partition与argpartition函数
#ndarray.partition(kth, axis=-1, kind='introselect', order=None)
#对指定的元素排序,默认是最后一个坐标轴
m = np.array ( [ 5, 2, 7, 1, 8, 3, 4, 6 ] )
print ( m.partition ( 1 ) ) #找出第1大的数据,放在1的位置,小的放前面,大的放后面
print ( m )
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.partition ( 1 ) ) #找出每行中列第1大的
print ( m )
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.partition ( 1, axis = 0 ) ) #找出每列中行第1大的
print ( m )
m = np.array ( [ 5, 2, 7, 1, 8, 3, 4, 6 ] )
print ( m.partition ( ( 1 , 5 ) ) ) #找出第1与5大的数据,放在1与5的位置,小的放前面,大的放后面
print ( m )
None
[1 2 7 5 8 3 4 6]
None
[[1 3 4 6]
[0 1 2 4]
[1 2 4 7]]
None
[[1 2 1 0]
[2 4 3 1]
[4 7 4 6]]
None
[1 2 3 4 5 6 7 8]
#ndarray.argpartition(kth, axis=-1, kind='introselect', order=None)
#返回下标
m = np.array ( [ 5, 2, 7, 1, 8, 3, 4, 6 ] )
print ( m.argpartition ( 1 ) ) #找出第1大的数据,放在1的位置,小的放前面,大的放后面
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.argpartition ( 1 ) ) #找出每行中列第1大的
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.argpartition ( 1, axis = 0 ) ) #找出每列中行第1大的
m = np.array ( [ 5, 2, 7, 1, 8, 3, 4, 6 ] )
print ( m.argpartition ( ( 1 , 5 ) ) ) #找出第1与5大的数据,放在1与5的位置,小的放前面,大的放后面
[3 1 2 0 4 5 6 7]
[[0 2 1 3]
[3 2 1 0]
[3 0 2 1]]
[[0 1 1 1]
[2 0 0 2]
[1 2 2 0]]
[3 1 5 6 0 7 2 4]
四、数组计算处理
数组计算操作方法 | 方法说明 |
---|---|
ndarray.argmax([axis, out]) | Return indices of the maximum values along the given axis. |
ndarray.min([axis, out, keepdims]) | Return the minimum along a given axis. |
ndarray.argmin([axis, out]) | Return indices of the minimum values along the given axis of a. |
ndarray.ptp([axis, out]) | Peak to peak (maximum - minimum) value along a given axis. |
ndarray.clip([min, max, out]) | Return an array whose values are limited to [min, max]. |
ndarray.conj() | Complex-conjugate all elements. |
ndarray.round([decimals, out]) | Return a with each element rounded to the given number of decimals. |
ndarray.trace([offset, axis1, axis2, dtype, out]) | Return the sum along diagonals of the array. |
ndarray.sum([axis, dtype, out, keepdims]) | Return the sum of the array elements over the given axis. |
ndarray.cumsum([axis, dtype, out]) | Return the cumulative sum of the elements along the given axis. |
ndarray.mean([axis, dtype, out, keepdims]) | Returns the average of the array elements along given axis. |
ndarray.var([axis, dtype, out, ddof, keepdims]) | Returns the variance of the array elements, along given axis. |
ndarray.std([axis, dtype, out, ddof, keepdims]) | Returns the standard deviation of the array elements along given axis. |
ndarray.prod([axis, dtype, out, keepdims]) | Return the product of the array elements over the given axis |
ndarray.cumprod([axis, dtype, out]) | Return the cumulative product of the elements along the given axis. |
ndarray.all([axis, out, keepdims]) | Returns True if all elements evaluate to True. |
ndarray.any([axis, out, keepdims]) | Returns True if any of the elements of a evaluate to True. |
【注意】:axis取值None,表示第一维度,其他值表示对应的维度。
这些函数在numpy都存在对应的函数
1. max、argmax函数与min、argmin函数
#ndarray.argmax(axis=None, out=None) 返回最大值下标
m = np.array ( [ 5, 8, 7, 1, 8, 3, 4, 6 ] )
print ( m.argmax ( ) ) #只返回第一个最大值
#ndarray.max(axis=None, out=None) 返回最大值下标
print ( m.max ( ) )
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.argmax ( ) )
print ( m.max ( ) )
print ( m.max ( axis = 0 ) ) #每列最大值
print ( m.max ( axis = 1 ) ) #每行最大值
1
8
9
7
[4 7 4 6]
[6 4 7]
#ndarray.argmin(axis=None, out=None) 返回最大值下标
m = np.array ( [ 5, 8, 7, 1, 8, 3, 4, 6 ] )
print ( m.argmin ( ) ) #只返回第一个最大值
#ndarray.min(axis=None, out=None) 返回最大值下标
print ( m.min ( ) )
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.argmin ( ) )
print ( m.min ( ) )
print ( m.min ( axis = 0 ) ) #每列最大值
print ( m.min ( axis = 1 ) ) #每行最大值
3
1
7
0
[1 2 1 0]
[1 0 1]
2. sum与cumsum函数
#ndarray.sum(axis=None, dtype=None, out=None, keepdims=False) #求和
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.sum ( ) )
print ( m.sum ( keepdims = True ) )
print ( m.sum ( dtype = np.float32 ) )
print ( m.sum ( axis = 0 ) ) #每列想加
print ( m.sum ( axis = 0, keepdims = True ) )
35
[[35]]
35.0
[ 7 13 8 7]
[[ 7 13 8 7]]
#ndarray.cumsum(axis=None, dtype=None, out=None) #累加和
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.cumsum ( ) )
print ( m.cumsum ( dtype = np.float32 ) )
print ( m.cumsum ( axis = 0 ) ) #按照行每列累加
[ 1 5 8 14 18 20 21 21 23 30 34 35]
[ 1. 5. 8. 14. 18. 20. 21. 21. 23. 30. 34. 35.]
[[ 1 4 3 6]
[ 5 6 4 6]
[ 7 13 8 7]]
3. trace函数
#ndarray.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
# 返回对角线的和
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.trace ( ) ) #对角线1,2,4 (偏移为0 )的和
print ( m.trace ( offset = 1 ) ) #对角线4,1,1(偏移为1,行的偏移)的和
print ( m.trace ( offset =1, axis1 = 1, axis2 = 0 ) ) #对角线4,7(偏移为1, 列的偏移)的和
7
6
11
4. mean函数
# ndarray.mean(axis=None, dtype=None, out=None, keepdims=False)
# 求均值
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.mean ( ) ) #全部元素的平均值
print ( m.mean ( dtype = np.float_ ) ) #全部元素的平均值
print ( m.mean ( keepdims = True) ) #全部元素的平均值
print ( m.mean ( axis = 0 ) ) #行的平均值(行想加,除以行数)
print ( m.mean ( axis = ( 0, 1 ) ) ) #行列的平均值
2.9166666666666665
2.9166666666666665
[[2.91666667]]
[2.33333333 4.33333333 2.66666667 2.33333333]
2.9166666666666665
5. std与var函数
方差用来度量随机变量和其数学期望(即均值)之间的偏离程度。
概率论中的方差表示方法 :
( 1 ) 样本方差:无偏估计、无偏方差
( 2 ) 总体方差:有偏估计、有偏方差、标准差、均方差
标准方差:
无偏方差:
说明:标准差就是偏差的均值(偏差就是样本与均值的差的平方和)
关于无偏方差,无偏估计的推导可以回顾大学的概率与数理统计
样本偏差:
总体偏差:
#ndarray.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False)
#标准方差
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.var ( ) )
#下面是等价计算方式
mn=m.mean ( ) # 平均值
#print ( mn )
m=m-mn #计算差
#print ( m )
m=m*m #差的平方
#print ( m ) #差的平方的均值
print ( m.mean ( ) )
4.243055555555556
4.243055555555556
#ndarray.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False)
#标准偏差
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.std ( ) )
# 下面是标准偏差的计算方式
print ( np.sqrt ( m.var ( ) ) )
2.0598678490513795
2.0598678490513795
理解上面偏差与方差区别后,下面可以讨论复杂点的参数了
#ndarray.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False)
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.var ( axis = 0 ) )
print ( [ m [ : , 0 ].var ( ), m [ : , 1 ].var ( ), m [ : , 2 ].var ( ), m [ : , 3 ].var ( ) ] )
[1.55555556 4.22222222 1.55555556 6.88888889]
[1.5555555555555556, 4.222222222222222, 1.5555555555555554, 6.888888888888889]
参数ddof的意义是用来控制有偏(n)与无偏(n - ddof)的计算方式,ddof默认是0:有偏;ddof=1:无偏
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 0 ],
[ 2, 7, 4, 1 ]
] )
print ( m.var ( ddof = 1 ) )
print ( m.var ( ddof = 0 ) )
print ( m.var ( ) )
4.628787878787879
4.243055555555556
4.243055555555556
6. prod与cumprod函数
积与累乘积
# ndarray.prod(axis=None, dtype=None, out=None, keepdims=False)
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 3 ],
[ 2, 7, 4, 1 ]
] )
print ( m.prod ( ) )
96768
#ndarray.cumprod(axis=None, dtype=None, out=None)
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 3 ],
[ 2, 7, 4, 1 ]
] )
print ( m.cumprod ( ) )
[ 1 4 12 72 288 576 576 1728 3456 24192 96768 96768]
6. all与any函数
#ndarray.all(axis=None, out=None, keepdims=False)
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 3 ],
[ 2, 7, 4, 1 ]
] )
print ( m.all ( ) )
True
#ndarray.any(axis=None, out=None, keepdims=False)
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 3 ],
[ 2, 7, 4, 1 ]
] )
print ( m.any ( ) )
True
五、数组算术运算
比较运算
运算符方法 | 方法说明 |
---|---|
ndarray.__lt__($self, value, /) | Return self<value. |
ndarray.__le__($self, value, /) | Return self<=value. |
ndarray.__gt__($self, value, /) | Return self>value. |
ndarray.__ge__($self, value, /) | Return self>=value. |
ndarray.__eq__($self, value, /) | Return self==value. |
ndarray.__ne__($self, value, /) | Return self!=value. |
数组作为逻辑值使用运算
运算符方法 | 方法说明 |
---|---|
ndarray.__nonzero__($self, /) | 返回bool值 |
单目运算方法
单目运算方法 | 方法说明 |
---|---|
ndarray.__neg__($self, /) | -self |
ndarray.__pos__($self, /) | +self |
ndarray.__abs__($self)
ndarray.__invert__($self, /) |~self
算术运算
算术运算符方法 | 方法说明 | |
---|---|---|
ndarray.__add__($self, value, /) | Return self+value. | |
ndarray.__sub__($self, value, /) | Return self-value. | |
ndarray.__mul__($self, value, /) | Return self*value. | |
ndarray.__div__($self, value, /) | Return self/value.(Python3) | |
ndarray.__truediv__($self, value, /) | Return self/value.(Python2) | |
ndarray.__floordiv__($self, value, /) | Return self//value. | |
ndarray.__mod__($self, value, /) | Return self%value. | |
ndarray.__divmod__($self, value, /) | Return divmod(self, value). | |
ndarray.__pow__($self, value[, mod]) | Return pow(self, value, mod). | |
ndarray.__lshift__($self, value, /) | Return self<<value. | |
ndarray.__rshift__($self, value, /) | Return self>>value. | |
ndarray.__and__($self, value, /) | Return self&value. | |
ndarray.__or__($self, value, /) | Return self | value. |
ndarray.__xor__($self, value, /) | Return self^value. |
【注意】:
- pow的第三个参数总是忽略的。
- 除法默认是__div__,__truediv__在设置__future__后使用(主要在Python2兼容Python3语法使用)。
- 可以使用set_numeric_ops方式设置调用的算术方法。
复合算术运算
复合算术运算符方法 | 方法说明 |
---|---|
ndarray.__iadd__($self, value, /) | Return self+=value. |
ndarray.__isub__($self, value, /) | Return self-=value. |
ndarray.__imul__($self, value, /) | Return self*=value. |
ndarray.__idiv__($self, value, /) | Return self/=value. |
ndarray.__itruediv__($self, value, /) | Return self/=value. |
ndarray.__ifloordiv__($self, value, /) | Return self//=value. |
ndarray.__imod__($self, value, /) | Return self%=value. |
ndarray.__ipow__($self, value, /) | Return self**=value. |
ndarray.__ilshift__($self, value, /) | Return self<<=value. |
ndarray.__irshift__($self, value, /) | Return self>>=value. |
ndarray.__iand__($self, value, /) | Return self&=value. |
ndarray.__ior__($self, value, /) | Return self|=value. |
ndarray.__ixor__($self, value, /) | Return self^=value. |
ndarray.__matmul__($self, value, /) | Return self@value. |
【注意】:a {op} b运算与 a {op}=b运算是有区别的,主要在类型转换上的区别。
六、其他运算
标准库函数操作
标准库操作方法 | 方法说明 |
---|---|
ndarray.__copy__() | Used if copy.copy is called on an array. |
ndarray.__deepcopy__(memo, /) | Used if copy.deepcopy is called on an array. |
ndarray.__reduce__() | For pickling. |
ndarray.__setstate__(state, /) | For unpickling. |
基本构造
基本构造方法 | 方法说明 |
---|---|
ndarray.__new__($type, *args, **kwargs) | Create and return a new object. |
ndarray.__array__(|dtype) | Returns either a new reference to self if dtype is not given or a new array of provided data type if dtype is different from the current dtype of the array. |
ndarray.__array_wrap__(obj) |
容器操作
容器操作方法 | 方法说明 |
---|---|
ndarray.__len__($self, /) | Return len(self). |
ndarray.__getitem__($self, key, /) | Return self[key]. |
ndarray.__setitem__($self, key, value, /) | Set self[key] to value. |
ndarray.__contains__($self, key, /) | Return key in self. |
类型转换
类型转换操作方法 | 方法说明 |
---|---|
ndarray.__int__(self) | |
ndarray.__long__ | |
ndarray.__float__(self) | |
ndarray.__oct__ | |
ndarray.__hex__ |
字符串转换
字符串转换操作方法 | 方法说明 |
---|---|
ndarray.__str__($self, /) | Return str(self). |
ndarray.__repr__($self, /) | Return repr(self). |
#__int__ 只作用于一个元素的数组,多于一个会错误
m = np.array ( [ 3 ] )
print ( int ( m ) )
3
m = np.array ( [
[ 1, 4, 3, 6 ],
[ 4, 2, 1, 3 ],
[ 2, 7, 4, 1 ]
] )
x = np.array ( [1,2,3,4] )
print ( m @ x)
# print ( x @ m) 不满足内积的条件
y = np.array ( [1,2,3] )
print ( y @ m)
[42 23 32]
[15 29 17 15]
资源
本文的ipynb文件下载【 ndarray_method.ipynb 】
提示:ndarray的很多成员函数,在numpy模块中都提供了对应的模块函数。