06.numpy聚合运算
>>> import numpy as np >>> L = np.random.random(100) >>> L array([0.82846513, 0.19136857, 0.27040895, 0.56103442, 0.90238039, 0.85178834, 0.41808196, 0.39347627, 0.01622051, 0.29921337, 0.35377822, 0.89350267, 0.78613657, 0.77138693, 0.42005486, 0.77602514, 0.46430814, 0.18177017, 0.8840256 , 0.71879227, 0.6718813 , 0.25656363, 0.43080182, 0.01645358, 0.23499383, 0.51117131, 0.29200924, 0.50189351, 0.49827313, 0.10377152, 0.44644312, 0.96918917, 0.73847112, 0.71955061, 0.89304339, 0.96267468, 0.19705023, 0.71458996, 0.16192394, 0.86625477, 0.62382025, 0.95945512, 0.52414204, 0.03643288, 0.72687158, 0.00390984, 0.050294 , 0.99199232, 0.2122575 , 0.94737066, 0.45154055, 0.99879467, 0.64750149, 0.70224071, 0.42958177, >>> sum(L) 52.03087325680787 >>> np.sum(L) 52.030873256807865
big_array = np.random.rand(1000000) >>> np.min(big_array) 4.459899819675428e-06 >>> big_array.max() 0.9999999038835905 >>> X = np.arange(16).reshape(4,4) >>> X array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> np.sum(X) 120 >>> np.sum(X,axis=0) array([24, 28, 32, 36]) >>> np.sum(X,axis=1) array([ 6, 22, 38, 54]) >>> np.prod(X) 0 >>> np.prod(X + 1) 2004189184 >>> np.mean(X) 7.5 >>> np.median(X) 7.5 >>> V = np.array([1,1,2,2,10]) >>> np.mean(V) 3.2 >>> np.median(V) 2.0 >>> np.percentile(big_array,q=50) 0.499739362948878 >>> for percent in [0,25,50,75,100]: ... print(np.percentile(big_array,q=percent)) ... 4.459899819675428e-06 0.24975691457362903 0.499739362948878 0.7498092671305248 0.9999999038835905 >>> X = np.random.normal(0,1,size=1000000) >>> np.mean(X) 0.00026937497963613595 >>> np.std(X) 0.9996291605602685 >>> np.min(X) -5.333919783687649 >>> np.argmin(X) 661675 >>> np.argmax(X) 774515 >>> X[91952] -0.5633231945005146 >>> np.max(X) 4.53612178954408 >>> x = np.arange(16) >>> x array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) >>> np.random.shuffle(x) >>> x array([ 2, 7, 8, 4, 14, 15, 6, 11, 13, 1, 12, 0, 9, 10, 3, 5]) >>> np.sort(x) array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) >>> x.sort() >>> x array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) >>> x = np.random.randint(10, size=(4,4)) >>> x array([[7, 0, 0, 7], [0, 3, 5, 7], [9, 7, 3, 9], [4, 0, 9, 2]]) >>> np.sort(x) array([[0, 0, 7, 7], [0, 3, 5, 7], [3, 7, 9, 9], [0, 2, 4, 9]]) >>> np.sort(x,axis=0) array([[0, 0, 0, 2], [4, 0, 3, 7], [7, 3, 5, 7], [9, 7, 9, 9]]) >>> np.partition(X,3) array([-5.33391978, -5.13221775, -4.86828137, ..., 0.16378629, 1.09224809, 1.00502282])