tolist函數將NumPy數群組轉換成Python列表。
In: bOut: array([ 1.+1.j, 3.+2.j])In: b.tolist()Out: [(1+1j), (3+2j)]
astype函數可以在轉換數組時指定資料類型。
In: bOut: array([ 1.+1.j, 3.+2.j])In: b.astype(int)/usr/local/bin/ipython:1: ComplexWarning: Casting complex values to real discards the imaginary part #虛部丟失,轉為b.astype('complex') 則不會發生錯誤。#!/usr/bin/pythonOut: array([1, 3])3.2 讀寫檔案
savetxt
import numpy as npi2 = np.eye(2)np.savetxt("eye.txt", i2)
# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800c,v=np.loadtxt('data.csv', delimiter=',', usecols=(6,7), unpack=True) #index從0開始
averages = np.zeros(5)for i in range(5): indices = np.where(dates == i) prices = np.take(close, indices) #按數組的元素運算,產生一個數組作為輸出。>>> a = [4, 3, 5, 7, 6, 8]>>> indices = [0, 1, 4]>>> np.take(a, indices)array([4, 3, 6])
格式字串以一個百分比符號開始。接下來是一個可選的標誌字元:-表示結果靠左對齊,0表示左端補0,+表示輸出符號(正號+或負號-)。第三部分為可選的輸出寬度參數,表示輸出的最小位元。第四部分是精度格式符,以”.”開頭,後面跟一個表示精度的整數。最後是一個類型指定字元,在例子中指定為字串類型。
numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)
>>> def my_func(a):... """Average first and last element of a 1-D array"""... return (a[0] + a[-1]) * 0.5>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])>>> np.apply_along_axis(my_func, 0, b) #沿著X軸運動,取列切片array([ 4., 5., 6.])>>> np.apply_along_axis(my_func, 1, b) #沿著y軸運動,取行切片array([ 2., 5., 8.])>>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])>>> np.apply_along_axis(sorted, 1, b)array([[1, 7, 8], [3, 4, 9], [2, 5, 6]])
(1) 使用ones函數建立一個長度為N的元素均初始化為1的數組,然後對整個數組除以N,即可得到權重。如下所示:
N = int(sys.argv[1])weights = np.ones(N) / Nprint "Weights", weights
在N = 5時,輸出結果如下:
Weights [ 0.2 0.2 0.2 0.2 0.2] #權重相等
(2) 使用這些權重值,調用convolve函數:
c = np.loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True)sma = np.convolve(weights, c)[N-1:-N+1] #卷積是分析數學中一種重要的運算,定義為一個函數與經過翻轉和平移的另一個函數的乘積的積分。t = np.arange(N - 1, len(c)) #作圖plot(t, c[N-1:], lw=1.0)plot(t, sma, lw=2.0)show()
指數移動平均(exponential moving average)。指數移動平均使用的權重是指數衰減的。對曆史上的資料點賦予的權重以指數速度減小,但永遠不會到達0。
x = np.arange(5)print "Exp", np.exp(x)#outputExp [ 1. 2.71828183 7.3890561 20.08553692 54.59815003]
Linspace 返回一個元素值在指定的範圍內均勻分布的數組。
print "Linspace", np.linspace(-1, 0, 5) #起始值、終止值、可選的元素個數#output Linspace [-1. -0.75 -0.5 -0.25 0. ]
(1)權重計算
N = int(sys.argv[1])weights = np.exp(np.linspace(-1. , 0. , N))
(2)權重歸一化處理
weights /= weights.sum()print "Weights", weights#outputWeights [ 0.11405072 0.14644403 0.18803785 0.24144538 0.31002201]
(3)計算及作圖
c = np.loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True)ema = np.convolve(weights, c)[N-1:-N+1]t = np.arange(N - 1, len(c))plot(t, c[N-1:], lw=1.0)plot(t, ema, lw=2.0)show()
(x, residuals, rank, s) = np.linalg.lstsq(A, b) #係數向量x、一個殘差數組、A的秩以及A的奇異值print x, residuals, rank, s#計算下一個預測值print np.dot(b, x)
>>> x = np.arange(6)>>> x = x.reshape((2, 3))>>> xarray([[0, 1, 2], [3, 4, 5]])>>> np.ones_like(x) #用1填充數組array([[1, 1, 1], [1, 1, 1]])
a = np.arange(4)print aprint "Compressed", a.compress(a > 2) #返回一個根據給定條件式篩選後的數組#output[0 1 2 3]Compressed [3]
b = np.arange(1, 9)print "b =", bprint "Factorial", b.prod() #輸出數組元素階乘結果#outputb = [1 2 3 4 5 6 7 8]Factorial 40320print "Factorials", b.cumprod()#outputFactorials [ 1 2 6 24 120 720 5040 40320] #數組元素遍曆階乘
4.2 股票相關性分析
covariance = np.cov(a,b)
詳解共變數與共變數矩陣
檢查一致性
np.array_equal(a, b)
np.vectorize 替代迴圈
>>> def myfunc(a, b):... "Return a-b if a>b, otherwise return a+b"... if a > b:... return a - b... else:... return a + b>>> vfunc = np.vectorize(myfunc)>>> vfunc([1, 2, 3, 4], 2)array([3, 4, 1, 2])
兩個多項式做差運算
poly_sub = np.polysub(a, b)
選擇函數
numpy.select(condlist, choicelist, default=0)
>>> x = np.arange(10)>>> condlist = [x<3, x>5] #輸出兩個array [true...false...],[false,...true]>>> choicelist = [x, x**2]>>> np.select(condlist, choicelist) array([ 0, 1, 2, 0, 0, 0, 36, 49, 64, 81])