Numpy的常用函数总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MOU_IT/article/details/81878027

1、np.argmax()、np.max()、np.argmin()、np.min()用法:

  argmax返回的是最大数的索引.argmax有一个参数axis,默认是0。看二维的情况如下:

a = np.array([[1, 5, 5, 2],
              [9, 6, 2, 8],
              [3, 7, 9, 1]])
print(np.argmax(a, axis=0))
[1,2,2,1]  # 返回列表的长度为最里层元素的长度

a = np.array([[1, 5, 5, 2],
              [9, 6, 2, 8],
              [3, 7, 9, 1]])
print(np.argmax(a, axis=1))
[1,0,2]   # 返回列表的长度为次里层元素的长度

    argmax()返回的是元素的索引,而max()返回的则是元素值,max的用法和argmax相似,也有一个axis的参数。同理,argmin()和min()也是相同的用法。

2、np.where(condition[, x, y])

  1)这里x,y是可选参数,condition是条件,这三个输入参数都是array_like的形式;而且三者的维度相同
  2)当conditon的某个位置的为true时,输出x的对应位置的元素,否则选择y对应位置的元素;
  3)如果只有参数condition,则函数返回为true的元素的坐标位置信息;

x = np.arange(9.).reshape(3, 3)
[[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]]
print (np.where( x > 5 ))
(array([2, 2, 2]), array([0, 1, 2]))

返回值其实是:
x[2, 0], x[2, 1], x[2, 2]

3、np.random中shuffle与permutation的区别

    函数np.shuffle()与np.permutation()都是对原来的数组进行重新洗牌(即随机打乱原来的元素顺序),区别在于:

    shuffle直接在原来的数组上进行操作,改变原来数组的顺序,无返回值。而permutation不直接在原来的数组上进行操作,而是返回一个新的打乱顺序的数组,并不改变原来的数组。

4、np.ascontiguousarray():返回和传入的数组类似的内存中连续的数组

 x = np.arange(6).reshape(2,3)
 print (np.ascontiguousarray(x, dtype=np.float32))
 print (x.flags['C_CONTIGUOUS'])

输出:
[[0. 1. 2.]
 [3. 4. 5.]]
True

5、np.empty():返回没有初始化的数组,它的值是随机的  

print (np.empty([2, 2]))

输出:
[[ 0.00000000e+000 -8.77796459e-313]
 [ 1.40447433e-311  6.17582057e-322]]

6、np.newaxis:为数组增加一个轴

x = np.arange(3) 
print (x)
y=x[:, np.newaxis]
print (y)

输出:
array([0, 1, 2])
array([[0], [1], [2]])

7、np.tile():将矩阵横向、纵向地复制

a=np.array([[1,2], [3, 4]])
print (a)
[[1 2]
 [3 4]]
print (np.tile(a, (1, 4)))  # 从最深的维度扩展到原来的4倍
[[1 2 1 2 1 2 1 2]
 [3 4 3 4 3 4 3 4]]
print (np.tile(a, (3, 1)))  # 从次深的维度扩展到原来的3倍
[[1 2]
 [3 4]
 [1 2]
 [3 4]
 [1 2]
 [3 4]]
print (np.tile(a, (3, 4)))  # 首先最深的维度扩展4倍,然后次深的维度扩展3倍
[[1 2 1 2 1 2 1 2]
 [3 4 3 4 3 4 3 4]
 [1 2 1 2 1 2 1 2]
 [3 4 3 4 3 4 3 4]
 [1 2 1 2 1 2 1 2]
 [3 4 3 4 3 4 3 4]]

8、np.sort()和np.argsort():第一个返回从小到大的排序值,第二个返回从小到大的索引

a=np.array([1,3,2,4])    
print (np.sort(a))     # 返回从小到大的排序
[1 2 3 4]
print (np.argsort(a))  # 返回从小到大的排序索引
[0 2 1 3]
print (np.argsort(-a)) # 返回从大到小的排序索引
[3 1 2 0]

9、np.cumsum():返回当前列之前的和加到当前列上的数组

a=[1,2,3,4,5,6,7]
print (np.cumsum(a))
[ 1  3  6 10 15 21 28]
c=[[1,2,3],[4,5,6],[7,8,9]]
print (np.cumsum(c,axis=0))  # 0(第一行不动,其他行累加)
[[ 1  2  3]
 [ 5  7  9]
 [12 15 18]]
print (np.cumsum(c,axis=1))  # 1(第一列列不动,其他列累加)
[[ 1  3  6]
 [ 4  9 15]
 [ 7 15 24]]

猜你喜欢

转载自blog.csdn.net/MOU_IT/article/details/81878027