numpy基本使用

numpy是python中科學計算不可或缺的庫

import numpy as np
x #x為一個數組
函數名 用法 解釋
sqrt np.sqrt(x) 計算數組元素的平方根
log np.log(x) 計算數組元素的自然對數
arange np.arange(m,n) 生成一個指定范圍的數組
astype np.astype(x) 把數組元素轉化為特定的數據類型
sum() np.sum(x) 計算數組元素之和

np.ceil():對數組元素向上取整

x  = array([2.9,3.2,5.19])
print(np.ceil(x))
[ 3.  4.  6.]

np.modf:返回浮點數的小數部分和整數部分

x  = array([2.9,3.2,5.19])
print(np.modf(x))
(array([ 0.9 ,  0.2 ,  0.19]), array([ 2.,  3.,  5.]))

np.where():返回符合條件的數組元素的索引值

x = array([1.,2.,3.4,5.0])
f = np.modf(x)[0]

In [57]: indices = np.where(f==0)
In [58]: indices
Out[58]: (array([0, 1, 3], dtype=int64),)

np.ravel():返回一個展開的一維數組

np.take():從數組中取出指定元素

In [61]: x = np.arange(10)
In [62]: indices = np.where(x%2==0)
In [63]: y = np.take(x,indices)
In [64]: y
Out[64]: array([[0, 2, 4, 6, 8]])

尋找回文數:np.outer(),np.raval()

import numpy as np
import numpy.testing
#尋找三位數字乘積的最大回文數
a = np.arange(100,1000)
n = np.outer(a,a) # 返回數組的外積
n = np.ravel(n)   # 返回一個展開的一維數組
n.sort()

for i in range(-1,-1*len(n),-1):
    s = str(n[i])
    if s == s[::-1]:
        print(s)
        break
print:906609

篩選法求質數

#求第10001個質數
import numpy as np
LIM = 10**6
N = 10**9
P = 10001
primes = []
p=2
def check_primes(a,p):
    a = a[a%p!=0]
    return a
for i in range(3,N,LIM):
    a = np.arange(i,i+LIM,2)
    while len(primes)<P:
        a = check_primes(a,p)
        primes.append(p)
        p = a[0]
print(len(primes),primes[P-1])

np.cumsum

>>> a = np.array([[1,2,3], [4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.cumsum(a)
array([ 1,  3,  6, 10, 15, 21])
>>> np.cumsum(a, dtype=float)     # specifies type of output value(s)
array([  1.,   3.,   6.,  10.,  15.,  21.])
>>>
>>> np.cumsum(a,axis=0)      # sum over rows for each of the 3 columns
array([[1, 2, 3],
       [5, 7, 9]])
>>> np.cumsum(a,axis=1)      # sum over columns for each of the 2 rows
array([[ 1,  3,  6],
       [ 4,  9, 15]])
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容