Python資料分析基礎教程:Numpy學習指南__Python

來源:互聯網
上載者:User
第二章 Numpy基礎 2.6 改變數組維度

ravel()、flatten() 將多維陣列展平

b.transpose() 矩陣轉置,等同於b.T,一維數組不變

reshape() 改變數組維度 2.8 組合數組

hstack((a, b)) 水平組合,等同於 concatenate((a, b), axis=1)
vstack((a, b)) 垂直組合,等同於 concatenate((a, b), axis=0)

column_stack((a, b)) 列組合,二維等同於hstack
row_stack((a, b)) 行組合,二維等同與vstack
2.10 分割數組

In: aOut:array([[0, 1, 2],      [3, 4, 5],      [6, 7, 8]])In:hsplit(a, 3)    #水平分割,等同於 split(a,3,axis=1)Out:[array([[0],        [3],        [6]]),array ([[1],        [4],        [7]]),array ([[2],        [5],        [8]])]

vsplit(a,3) 垂直分割 ,等同於 split(a,3,axis=0) 2.11 數組屬性

ndim 數組維度,或數組軸的個數

size 數組元素總數

itemsize 數組元素在記憶體中所佔位元組數

nbytes 數組所佔儲存空間 = itemsize * size

b = array([1.j + 1, 2.j + 3]) 虛數
b.real 複數數組的實部 b.imag 虛部

flat屬性將返回一個numpy.flatiter對象,可以讓我們像遍曆一維數組一樣去遍曆任意的多維陣列。

In: b = arange(4).reshape(2,2)In: bOut:array([[0, 1],      [2, 3]])In: f = b.flatIn: fOut: <numpy.flatiter object at 0x103013e00>In: for item in f: print item.....:
2.12 數群組轉換

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)
3.4 讀入CSV檔案
# 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開始
3.6.1 算術平均值

np.mean(c) = np.average(c) 3.6.2 加權平均值

t = np.arange(len(c))
np.average(c, weights=t)
3.8 極值

np.min(c)
np.max(c)

np.ptp(c) 最大值與最小值的差值 3.10 統計分析

np.median(c) 中位元
np.msort(c) 升序排序
np.var(c) 方差
3.12 分析股票收益率

np.diff(c) 可以返回一個由相鄰數組元素的差
值構成的數組

returns = np.diff( arr ) / arr[ : -1]  #diff返回的數組比收盤價數組少一個元素

np.std(c) 標準差

對數收益率

logreturns = np.diff( np.log(c) )  #應檢查輸入數組以確保其不含有零和負數

where 可以根據指定的條件返回所有滿足條件的數
組元素的索引值。
posretindices = np.where(returns > 0)

np.sqrt(1./252.) 平方根,浮點數 3.14 分析日期資料

# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800dates, close=np.loadtxt('data.csv', delimiter=',', usecols=(1,6), converters={1:datestr2num}, unpack=True)print "Dates =", datesdef datestr2num(s):    return datetime.datetime.strptime(s, "%d-%m-%Y").date().weekday()# 星期一 0# 星期二 1# 星期三 2# 星期四 3# 星期五 4# 星期六 5# 星期日 6#outputDates = [ 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 1. 2. 4. 0. 1. 2. 3. 4. 0.1. 2. 3. 4.]
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])

np.argmax(c) #返回的是數組中最大元素的索引值
np.argmin(c)
3.16 摘要資料

# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800#得到第一個星期一和最後一個星期五first_monday = np.ravel(np.where(dates == 0))[0]last_friday = np.ravel(np.where(dates == 4))[-1]#建立一個數組,用於儲存三周內每一天的索引值weeks_indices = np.arange(first_monday, last_friday + 1)#按照每個子數組5個元素,用split函數切分數組weeks_indices = np.split(weeks_indices, 5)#output[array([1, 2, 3, 4, 5]), array([ 6, 7, 8, 9, 10]), array([11,12, 13, 14, 15])]weeksummary = np.apply_along_axis(summarize, 1, weeks_indices,open, high, low, close)def summarize(a, o, h, l, c): #open, high, low, closemonday_open = o[a[0]]week_high = np.max( np.take(h, a) )week_low = np.min( np.take(l, a) )friday_close = c[a[-1]]return("APPL", monday_open, week_high, week_low, friday_close)np.savetxt("weeksummary.csv", weeksummary, delimiter=",", fmt="%s") #指定了檔案名稱、需要儲存的數組名、分隔字元(在這個例子中為英文標點逗號)以及儲存浮點數的格式。

格式字串以一個百分比符號開始。接下來是一個可選的標誌字元:-表示結果靠左對齊,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]])
3.20 計算簡單移動平均線

(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()
3.22 計算指數移動平均

指數移動平均(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()
3.26 用線性模型預測價格
(x, residuals, rank, s) = np.linalg.lstsq(A, b) #係數向量x、一個殘差數組、A的秩以及A的奇異值print x, residuals, rank, s#計算下一個預測值print np.dot(b, x)
3.28 繪製趨勢線
>>> 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]])

類似函數
zeros_like
empty_like
zeros
ones
empty
3.30 數組的修剪和壓縮

a = np.arange(5)print "a =", aprint "Clipped", a.clip(1, 2) #將所有比給定最大值還大的元素全部設為給定的最大值,而所有比給定最小值還小的元素全部設為給定的最小值#outputa = [0 1 2 3 4]Clipped [1 1 2 2 2]
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)

詳解共變數與共變數矩陣

擷取對角元素
covariance.diagonal()
4.4 多項式擬合

bhp=np.loadtxt('BHP.csv', delimiter=',', usecols=(6,), unpack=True)vale=np.loadtxt('VALE.csv', delimiter=',', usecols=(6,),unpack=True)t = np.arange(len(bhp))poly = np.polyfit(t, bhp - vale, int(sys.argv[1])) # sys.argv[1]為3,即用3階多項式擬合資料print "Polynomial fit", poly#outputPolynomial fit [ 1.11655581e-03 -5.28581762e-02 5.80684638e-01 5.79791202e+01]#預測下個值print "Next value", np.polyval(poly, t[-1] + 1)

使用polyder函數對多項式函數求導(以求極值)

der = np.polyder(poly)print "Derivative", der#outputDerivative [ 0.00334967 -0.10571635 0.58068464]

求出導數函數的根,即找出原多項式函數的極值點

print "Extremas", np.roots(der)#outputExtremas [ 24.47820054 7.08205278]

註:書中提示,3階多項式擬合資料的結果並不好,可嘗試更高階的多項式擬合。 4.6 計算OBV(On-Balance Volume)淨額成交量

diff函數可以計算數組中兩個連續元素的差值,並返回一個由這些差值組成的數組。
change = np.diff(c)

sign函數可以返回數組中每個元素的正負符號,數組元素為負時返回-1,為正時返回1,否則返回0
np.sign(change)

使用piecewise(分段的)函數來擷取數組元素的正負。使用合適的傳回值和對應的條件調用該函數:

pieces = np.piecewise(change, [change < 0, change > 0], [-1, 1])print "Pieces", pieces

檢查一致性
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])

The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop. 4.10 使用hanning 函數平滑資料

(1) 調用hanningFunction Compute權重,產生一個長度為N的視窗(在這個樣本中N取8)

N = int(sys.argv[1])weights = np.hanning(N)print "Weights", weights#outputWeights [ 0. 0.1882551 0.61126047 0.95048443 0.95048443 0.61126047 0.1882551 0. ]bhp = np.loadtxt('BHP.csv', delimiter=',', usecols=(6,),unpack=True)   #某股票資料bhp_returns = np.diff(bhp) / bhp[ : -1] #股票收益率計算smooth_bhp = np.convolve(weights/weights.sum(), bhp_returns) [N-1:-N+1]  #使用weights平滑股票收益率#繪圖t = np.arange(N - 1, len(bhp_returns))plot(t, bhp_returns[N-1:], lw=1.0)plot(t, smooth_bhp, lw=2.0)show()

兩個多項式做差運算
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])

trim_zeros函數可以去掉一維數組中開頭和末尾為0的元素:
np.trim_zeros(a) 5.2 建立矩陣(略)
5.4 從已有矩陣建立新矩陣(略) 5.6 建立通用函數(略) 5.7 通用函數的方法(略) 5.8 在add上調用通用函數的方法(略) 5.10 數組的除法運算

在NumPy中,基本算術運算子+、-和*隱式關聯著通用函數add、subtract和multiply。
也就是說,當你對NumPy數組使用這些算術運算子時,對應的通用函數將自動被調用。除法包含的過程則較為複雜,在數組的除法運算中涉及三個通用函數divide、true_divide和floor_division,以及兩個對應的運算子/和//。

a = np.array([2, 6, 5])b = np.array([1, 2, 3])print "Divide", np.divide(a, b), np.divide(b, a)#outputDivide [2 3 1] [0 0 0]print "True Divide", np.true_divide(a, b), np.true_divide(b, a)#outputTrue Divide [2. 3. 1.66666667] [0.5 0.33333333 0.6 ]print "Floor Divide", np.floor_divide(a, b), np.floor_divide(b, a) c = 3.14 * b   #floor_divide函數總是返回整數結果,相當於先調用divide函數再調用floor函數。print "Floor Divide 2", np.floor_divide(c, b), np.floor_divide(b, c) #floor函數將對浮點數進行向下取整並返回整數。#outputFloor Divide [

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.