Numpy、Pandas是Python數(shù)據(jù)處理中經(jīng)常用到的兩個(gè)框架,都是采用C語言編寫,所以運(yùn)算速度快。Matplotlib是Python的的畫圖工具,可以把之前處理后的數(shù)據(jù)通過圖像繪制出來。之前只是看過語法,沒有系統(tǒng)學(xué)習(xí)總結(jié)過,本博文總結(jié)了這三個(gè)框架的API。
以下是這三個(gè)框架的的簡(jiǎn)單介紹和區(qū)別:
Numpy:經(jīng)常用于數(shù)據(jù)生成和一些運(yùn)算 Pandas:基于Numpy構(gòu)建的,是Numpy的升級(jí)版本 Matplotlib:Python中強(qiáng)大的繪圖工具Numpy
Numpy快速入門教程可參考:Numpy tutorial
Numpy屬性
ndarray.ndim:維度
ndarray.shape:行數(shù)和列數(shù),例如(3, 5)
ndarray.size:元素的個(gè)數(shù)
ndarray.dtype:元素類型
Numpy創(chuàng)建
array(object, dtype=None):使用Python的list或者tuple創(chuàng)建數(shù)據(jù)
zeors(shape, dtype=float):創(chuàng)建全為0的數(shù)據(jù)
ones(shape, dtype=None):創(chuàng)建全為1的數(shù)據(jù)
empty(shape, dtype=float):創(chuàng)建沒有初始化的數(shù)據(jù)
arange([start, ]stop, [step, ]dtype=None):創(chuàng)建固定間隔的數(shù)據(jù)段
linspace(start, stop, num=50, dtype=None):在給定的范圍,均勻的創(chuàng)建數(shù)據(jù)
Numpy運(yùn)算
加、減:a + b、a - b
乘:b*2、10*np.sin(a)
次方:b**2
判斷:a<35,輸出True或False的數(shù)組
矩陣乘:np.dot(A,B) 或 A.dot(B)
其他:+=、-+、sin、cos、exp
Numpy索引
數(shù)組索引方式:A[1, 1]
切片:A[1, 1:3]
迭代:for item in A.flat
Numpy其他
reshape(a, newshape):改變數(shù)據(jù)形狀,不會(huì)對(duì)原始數(shù)據(jù)進(jìn)行修改,返回一組新數(shù)據(jù)
resize(a, new_shape):改變數(shù)據(jù)形狀,會(huì)對(duì)原始數(shù)據(jù)進(jìn)行修改,不返回?cái)?shù)據(jù)
ravel(a):將成一維返回
vstack(tup):上下合并
hstack(tup):左右合并
hsplit(ary, indices_or_sections):水平分割n份
vsplit(ary, indices_or_sections):垂直分割n份
copy(a):深度拷貝
Pandas
Pandas快速入門教程可參考:10 Minutes to pandas
Pandas數(shù)據(jù)結(jié)構(gòu)
Pandas的數(shù)據(jù)結(jié)構(gòu)有兩種:Series和DataFrame。
Series:索引在左邊,值在右邊。創(chuàng)建方式如下:
In [4]: s = pd.Series([1,3,5,np.nan,6,8])In [5]: sOut[5]: 0 1.01 3.02 5.03 NaN4 6.05 8.0dtype: float64
DataFrame:是一個(gè)表格型的數(shù)據(jù)結(jié)構(gòu),既有行索引也有列索引, 它可以被看做由Series組成的大字典。創(chuàng)建方式如下:
In [6]: dates = pd.date_range('20130101', periods=6)In [7]: datesOut[7]: DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04', '2013-01-05', '2013-01-06'], dtype='datetime64[ns]', freq='D')In [8]: df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
新聞熱點(diǎn)
疑難解答
圖片精選