numpy(4)数组的常用函数

where函数 

import numpy as np
a = np.array([1,2,3,4,5,6,0])
b = np.where(a>4,a,1)
print(b)

arr1 = np.array([10,20,30,0])
arr2 = np.array([2,3,4,0])
arr1,arr2 = arr1.astype(np.float16),arr2.astype(np.float16)
arr3 = np.zeros_like(arr1)
iszero = np.where(arr2==0)
nozero = np.where(arr2!=0)
arr3[nozero] = arr1[nozero]/arr2[nozero]
arr3[iszero] = np.nan
print(arr3)

x,y = np.ogrid[:3,:4]  #ogrid生成一个二维数组
print(x,y)  
k = np.where(x<y,x,y+10)  
print(k)


[1 1 1 1 5 6 1]


[5.    6.668 7.5     nan]


[[0]
 [1]
 [2]] [[0 1 2 3]]


[[10  0  0  0]
 [10 11  1  1]
 [10 11 12  2]]

统计函数

'''
计算两组数的相关系数
'''
import numpy as np
a = np.array([1.1,2,3,4,5,6])
b = np.array([1,2.3,3,5,5,6])
print(np.corrcoef(a,b))

[[1.         0.99977528]
 [0.99977528 1.        ]]

'''
求分位数
'''
import numpy as np
a = np.array([4,2,3,4,78,4])
b = np.quantile(a,0.5)
print(b)

4.0

axis参数 

'''
当axis=1时,结果为行统计指标,
当axis=0时,结果为列统计指标。
'''
import numpy as np
a = np.arange(9).reshape(3,3)
b = np.sum(a,axis=1)
c = np.sum(a,axis=0)
print(a)
print('---')
print(b)
print('----')
print(c)

[[0 1 2]
 [3 4 5]
 [6 7 8]]
---
[ 3 12 21]
----
[ 9 12 15]

数组之间的比较

返回数组,元素为bool值

'''
数组之间的比较
'''
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[1,0,2],[3,5,9]])
c = a > b
print(c)

[[False  True  True]
 [ True False False]]

上一篇:PHP array_merge和+的区别


下一篇:找出两数组的中位数 O(log n ) 分治与递归