1.数组值的求和

首先构造一个具有100个值的数组,然后我们利用两个不同的方法进行求和:

>>> l=np.random.random(100)

l的数据如下:

>>> l
array([0.63330856, 0.55254815, 0.681117  , 0.0392779 , 0.55515459,
       0.65577685, 0.93779694, 0.38145863, 0.15571406, 0.58656667,
       0.05014379, 0.22707423, 0.2206218 , 0.99183227, 0.067189  ,
       0.85587266, 0.38610259, 0.58482566, 0.21639326, 0.66505995,
       0.47360391, 0.553394  , 0.6861513 , 0.36460573, 0.25960476,
       0.80718606, 0.61228608, 0.47824396, 0.98466131, 0.13550462,
       0.2296882 , 0.41334125, 0.0028512 , 0.00706611, 0.66774287,
       0.26150011, 0.98494222, 0.16255418, 0.55893817, 0.63001863,
       0.0151125 , 0.13388626, 0.3116983 , 0.70979666, 0.36033375,
       0.70286921, 0.08094839, 0.38973694, 0.07205708, 0.23503885,
       0.56665754, 0.72277441, 0.00386346, 0.86161187, 0.09270819,
       0.36279124, 0.14414812, 0.83186456, 0.759372  , 0.26563921,
       0.5059324 , 0.35014357, 0.55575501, 0.5613696 , 0.00100515,
       0.40608559, 0.89754344, 0.13651899, 0.334764  , 0.77378823,
       0.69603667, 0.65702436, 0.98306105, 0.93510312, 0.71863035,
       0.14813637, 0.92719219, 0.3230562 , 0.36282925, 0.26928228,
       0.70444039, 0.03080534, 0.21334398, 0.14623021, 0.85840572,
       0.51886698, 0.40347232, 0.84893857, 0.17807356, 0.02207469,
       0.05365235, 0.47315195, 0.48036338, 0.54677648, 0.73090216,
       0.20840042, 0.0531166 , 0.59713323, 0.76020517, 0.50951197])

利用np里面的sum函数明显求和会更快,但是直接利用python当中的函数则会比较慢,这也是有科学依据的,但是我们只要记住即可,感兴趣的同学可以利用%timeit 来求出两个不同函数进行计算的时间:
计算结果如下:

>>> sum(l)
45.22175110164667
>>> np.sum(l)
45.221751101646674

 2.求解最大最小值

>>> np.min(l)
0.0010051507515725921
>>> np.max(l)
0.9918322686313938

3.多维度聚合

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
result = np.sum(arr)
print(result)

 

版权声明:本文为geeksongs原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/geeksongs/p/11015928.html