標籤:lambda cal eve cas dom 表示 資料處理 order python
http://www.cnblogs.com/batteryhp/p/5006274.html
pandas是本書後續內容的首選庫。pandas可以滿足以下需求:
- 具備按軸自動或顯式資料對齊功能的資料結構。這可以防止許多由於資料未對齊以及來自不同資料來源(索引方式不同)的資料而導致的常見錯誤。.
- 整合時間序列功能
- 既能處理時間序列資料也能處理非時間序列資料的資料結構
- 數學運算和簡約(比如對某個軸求和)可以根據不同的中繼資料(軸編號)執行
- 靈活處理缺失資料
- 合并及其他出現在常見資料庫(例如基於SQL的)中的關係型運算
1、pandas資料結構介紹
兩個資料結構:Series和DataFrame。Series是一種類似於以為NumPy數組的對象,它由一組資料(各種NumPy資料類型)和與之相關的一組資料標籤(即索引)組成的。可以用index和values分別規定索引和值。如果不規定索引,會自動建立 0 到 N-1 索引。
#-*- encoding:utf-8 -*-import numpy as npimport pandas as pdfrom pandas import Series,DataFrame#Series可以設定index,有點像字典,用index索引obj = Series([1,2,3],index=[‘a‘,‘b‘,‘c‘])#print obj[‘a‘]#也就是說,可以用字典直接建立Seriesdic = dict(key = [‘a‘,‘b‘,‘c‘],value = [1,2,3])dic = Series(dic)#下面注意可以利用一個字串更新索引值key1 = [‘a‘,‘b‘,‘c‘,‘d‘]#注意下面的語句可以將 Series 對象中的值提取出來,不過要知道的字典是不能這麼做提取的dic1 = Series(obj,index = key1)#print dic#print dic1#isnull 和 notnull 是用來檢測缺失資料#print pd.isnull(dic1)#Series很重要的功能就是按照索引值自動對齊功能dic2 = Series([10,20,30,40],index = [‘a‘,‘b‘,‘c‘,‘e‘])#print dic1 + dic2#name屬性,可以起名字dic1.name = ‘s1‘dic1.index.name = ‘key1‘#Series 的索引可以就地修改dic1.index = [‘x‘,‘y‘,‘z‘,‘w‘]
DataFrame是一種表格型結構,含有一組有序的列,每一列可以是不同的資料類型。既有行索引,又有列索引,可以被看做由Series組成的字典(使用共同的索引)。跟其他類似的資料結構(比如R中的data.frame),DataFrame面向行和列的操作基本是平衡的。其實,DataFrame中的資料是以一個或者多個二維塊存放的(不是列表、字典或者其他)。
#-*- encoding:utf-8 -*-import numpy as npimport pandas as pdfrom pandas import Series,DataFrame#構建DataFrame可以直接傳入等長的列表或Series組成的字典#不等長會產生錯誤data = {‘a‘:[1,2,3], ‘c‘:[4,5,6], ‘b‘:[7,8,9]}#注意是按照列的名字進行列排序frame = DataFrame(data)#print frame#指定列之後就會按照指定的進行排序frame = DataFrame(data,columns=[‘a‘,‘c‘,‘b‘])print frame#可以有空列,index是說行名frame1 = DataFrame(data,columns = [‘a‘,‘b‘,‘c‘,‘d‘],index = [‘one‘,‘two‘,‘three‘])print frame1#用字典方式取列資料print frame[‘a‘]print frame.b#列資料的修改直接選出來重新賦值即可#行,可以用行名或者行數來進行選取print frame1.ix[‘two‘]#為列賦值,如果是Series,規定了index後可以精確賦值frame1[‘d‘] = Series([100,200,300],index = [‘two‘,‘one‘,‘three‘])print frame1#刪除列用del 函數del frame1[‘d‘]#警告:通過列名選出來的是Series的視圖,並不是副本,可用Series copy方法得到副本
另一種常見的結構是嵌套字典,即字典的字典,這樣的結構會預設為外鍵為列,內列為行。
#-*- encoding:utf-8 -*-import numpy as npimport pandas as pdfrom pandas import Series,DataFrame#內層字典的索引值會被合并、排序以形成最終的索引pop = {‘Nevada‘:{2001:2.4,2002:2.9}, ‘Ohio‘:{2000:1.5,2001:1.7,2002:3.6}}frame3 = DataFrame(pop)#rint frame3#Dataframe也有行和列有name屬性,DataFrame有value屬性frame3.index.name = ‘year‘frame3.columns.name = ‘state‘print frame3print frame3.values
下面列出了DataFrame建構函式能夠接受的各種資料。
索引對象
#-*- encoding:utf-8 -*-import numpy as npimport pandas as pdfrom pandas import Series,DataFrame#pandas索引對象負責管理軸標籤和其他中繼資料,構建Series和DataFrame時,所用到的任何數組或其他序列的標籤都被轉換為Indexobj = Series(range(3),index = [‘a‘,‘b‘,‘c‘])index = obj.index#print index#索引對象是無法修改的,這非常重要,因為這樣才會使得Index對象在多個資料結構之間安全共用index1 = pd.Index(np.arange(3))obj2 = Series([1.5,-2.5,0],index = index1)print obj2.index is index1#除了長得像數組,Index的功能也類似一個固定大小的集合print ‘Ohio‘ in frame3.columnsprint 2003 in frame3.index
pandas中的Index是一個類,pandas中主要的Index對象(什麼時候用到)。
下面是Index的方法與屬性,值得注意的是:index並不是數組。
2、準系統
下面介紹基本的Series 和 DataFrame 資料處理手段。首先是索引:
#-*- encoding:utf-8 -*-import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom pandas import Series,DataFrame#Series有一個reindex函數,可以將索引重排,以致元素順序發生變化obj = Series([1,2,3,4],index=[‘a‘,‘b‘,‘c‘,‘d‘])#注意這裡的reindex並不改變obj的值,得到的是一個“副本”#fill_value 顯然是填充空的index的值#print obj.reindex([‘a‘,‘c‘,‘d‘,‘b‘,‘e‘],fill_value = 0)#print objobj2 = Series([‘red‘,‘blue‘],index=[0,4])#method = ffill,意味著前向值填充obj3 = obj2.reindex(range(6),method=‘ffill‘)#print obj3#DataFrame 的reindex可以修改行、列或者兩個都改frame = DataFrame(np.arange(9).reshape((3,3)),index = [‘a‘,‘c‘,‘d‘],columns = [‘Ohio‘,‘Texas‘,‘California‘])#只是傳入一列數,是對行進行reindex,因為...frame的行參數叫index...(我這麼猜的)frame2 = frame.reindex([‘a‘,‘b‘,‘c‘,‘d‘])#print frame2#當傳入原來沒有的index是,當然返回的是空NaN#frame3 = frame.reindex([‘e‘])#print frame3states = [‘Texas‘,‘Utah‘,‘California‘]#這是對行、列重排#注意:這裡的method是對index 也就是行進行的填充,列是不能填充的(不管method的位置如何)frame4 = frame.reindex(index = [‘a‘,‘b‘,‘c‘,‘d‘],columns=states,method = ‘ffill‘)#print frame4#使用ix的標籤索引功能,重新索引變得比較簡潔print frame.ix[[‘a‘,‘d‘,‘c‘,‘b‘],states]
關於ix,是DataFrame的一個方法,http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.ix.html。
丟棄指定軸上的項
#-*- encoding:utf-8 -*-import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom pandas import Series,DataFrame#drop函數可以丟棄軸上的列、行值obj = Series(np.arange(3.),index = [‘a‘,‘b‘,‘c‘])#原Series並不丟棄obj.drop(‘b‘)#print obj#注意下面,行可以隨意丟棄,列需要加axis = 1print frame.drop([‘a‘])print frame.drop([‘Ohio‘],axis = 1)
下面說索引、選取和過濾
#-*- encoding:utf-8 -*-import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom pandas import Series,DataFrameobj = Series([1,2,3,4],index=[‘a‘,‘b‘,‘c‘,‘d‘])frame = DataFrame(np.arange(9).reshape((3,3)),index = [‘a‘,‘c‘,‘d‘],columns = [‘Ohio‘,‘Texas‘,‘California‘])#Series切片和索引#print obj[obj < 2]#注意:利用標籤的切片與python的切片不同,兩端都是包含的(有道理)print obj[‘b‘:‘c‘]#對於DataFrame,列可以直接用名稱print frame[‘Ohio‘]#特殊情況:通過切片和bool型索引,得到的是行(有道理)print frame[:2]print frame[frame[‘Ohio‘] != 0]#下面的方式是對frame所有元素都適用,不是行或者列,下面的得到的是numpy.ndarray類型的資料print frame[frame < 5],type(frame[frame < 5])frame[frame < 5] = 0print frame#對於DataFrame上的標籤索引,用ix進行print frame.ix[[‘a‘,‘d‘],[‘Ohio‘,‘Texas‘]]print frame.ix[2] #注意這裡預設取行#注意下面預設取行print frame.ix[frame.Ohio > 0]#注意下面的逗號後面是列標print frame.ix[frame.Ohio > 0,:2]
下面是常用的索引選項:
算術運算和資料對齊
#pandas 有一個重要的功能就是能夠根據索引自動對齊,其中索引不重合的部分值為NaNs1 = Series([1,2,3],[‘a‘,‘b‘,‘c‘])s2 = Series([4,5,6],[‘b‘,‘c‘,‘d‘])#print s1 + s2df1 = DataFrame(np.arange(12.).reshape(3,4),columns=list(‘abcd‘))df2 = DataFrame(np.arange(20.).reshape(4,5),columns=list(‘abcde‘))#print df1 + df2#使用add方法,並傳入填儲值,注意下面的fill_value函數是先對應填充再進行加和,而不是加和得到NaN之後再填充#print df1.add(df2,fill_value = 1000)#df1.reindex(columns = df2.columns,fill_value=0)
除了add之外,還有其他的方法:
DataFrame和Series之間的運算
#下面看一下DataFrame和Series之間的計算過程arr = DataFrame(np.arange(12.).reshape((3,4)),columns = list(‘abcd‘))#下面的結果標明,就是按行分別相減即可,叫做 broadcasting#注意:預設情況下,DataFrame和Series的計算會將Series的索引匹配到DataFrame的列,然後進行計算,再沿著行一直向下廣播#注意:下面的式子中,如果寫arr - arr[0]是錯的,因為只有標籤索引函數ix後面加數字才表示行print arr - arr.ix[0]Series2 = Series(range(3),index = list(‘cdf‘))#按照規則,在不匹配的列會形成NaN值print arr + Series2#如果想匹配行且在列上廣播,需要用到算術運算方法Series3 = arr[‘d‘]#axis就是希望匹配的軸print arr.sub(Series3,axis = 0)
下面是函數應用和映射
#-*- encoding:utf-8 -*-import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom pandas import Series,DataFrame#NumPy的元素級數組方法也適用於pandas對象frame = DataFrame(np.random.randn(4,3),columns = list(‘abc‘),index = [‘Ut‘,‘Oh‘,‘Te‘,‘Or‘])print frame#下面是求絕對值:#print np.abs(frame)#另一種常見的做法是:將一個函數應用到行或者列上,用apply方法,與R語言類似fun = lambda x:x.max() - x.min()#預設是應用在每一列上print frame.apply(fun)#下面是應用在列上print frame.apply(fun,axis = 1)#很多統計函數根本不用apply,直接調用方法就可以了print frame.sum()#除了標量值之外,apply函數後面還可以接返回多個值組成的的Series的函數,有沒有很漂亮?def f(x): return Series([x.min(),x.max()],index = [‘min‘,‘max‘])#print frame.apply(f)#元素級的python函數也是可以用的,但是要使用applymap函數format = lambda x: ‘%.2f‘ % xprint frame.applymap(format)#之所以要用applymap是因為Series有一個應用於元素級函數的map方法??#這裡的map很有用print frame[‘b‘].map(format)
排序與排名
#-*- encoding:utf-8 -*-import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom pandas import Series,DataFrame#用sort_index函數對行、列的索引進行排序obj = Series(range(4),index = [‘d‘,‘a‘,‘b‘,‘c‘])print obj.sort_index()frame = DataFrame(np.arange(8).reshape((2,4)),index = [‘three‘,‘one‘],columns = [‘d‘,‘a‘,‘b‘,‘c‘])#預設是對行 “索引” 進行排序,如果對列 “索引” 進行排序,axis = 1 即可print frame.sort_index()print frame.sort_index(axis = 1)print frame.sort_index(axis = 1,ascending = False)#如果對值進行排序,用的是order函數,注意所有的缺失值會放到最後(如果有的話)print obj.order()#numpy中的sort也可以用來排序print np.sort(obj)#如果相對DataFrame的值進行排序,函數還是sort_index,只不過後面需要加一個參數byframe = DataFrame({‘b‘:[4,7,-3,2],‘a‘:[0,1,0,1]})print frame.sort_index(by = [‘a‘,‘b‘])#rank函數返回從小到大排序的下標,對於平級的數,rank是通過“為各組分配一個平均排名”的方式破壞評級關係#下標從1開始obj = Series([7,-5,7,4,2,0,4])print obj.rank()#而numpy中的argsort函數比較奇怪,返回的是把資料進行排序之後,按照值得順序對應的下標,下標從0開始print np.argsort(obj) #列印結果為:1,5,4,3,6,0,2 按照這個下標順序恰好可以得到從小打到的值,見下面print obj[np.argsort(obj)]#rank函數中有一個method選項,用來規定下標的方式print obj.rank(method = ‘first‘,ascending=False)print obj.rank(method = ‘max‘,ascending=False)print obj.rank(method = ‘min‘,ascending=False)#對於DataFrame,rank函數預設把每一列排好並返回座標print frame.rank()print frame.rank(axis = 1)
帶有重複值的軸索引
#-*- encoding:utf-8 -*-import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom pandas import Series,DataFrame#雖然pandas的很多函數(如reindex)要求標籤唯一,但是並不具有強制性obj = Series(range(5),index = list(‘aabbc‘))print obj#索引是否唯一用is_unique看是否唯一print obj.index.is_unique#對於重複值的索引,選取的話返回一個Series,唯一的索引返回一個標量print obj[‘a‘]#對於DataFrame也是如此df = DataFrame(np.random.randn(4,3),index = list(‘aabb‘))print dfprint df.ix[‘b‘]#####自己匯入資料的時候資料處理之前可以做一下index唯一性等,自己建立DataFrame注意不能這樣
3、匯總和計算描述統計
#-*- encoding:utf-8 -*-import numpy as npimport osimport pandas as pdfrom pandas import Series,DataFrameimport matplotlib.pyplot as pltimport time#pandas 對象擁有一組常用的數學和統計方法,大部分屬於簡約統計,用於從Series中提取一個值,或者 從DataFrame中提取一列或者一行Series#注意:與NumPy數組相比,這些函數都是基於沒有缺失資料的建設構建的,也就是說:這些函數會自動忽略缺失值。df = DataFrame([[1.4,np.nan],[7.1,-4.5],[np.nan,np.nan],[0.75,-1.3]],index = list(‘abcd‘),columns=[‘one‘,‘two‘])print df.sum()print df.sum(axis = 1)#下面是一些函數,idxmin 和 idmax 返回的是達到最小或者最大的索引print df.idxmin()print df.idxmin(axis=1)#關於累積型的函數print df.cumsum()#describe函數,與R語言中的describe函數基本相同print df.describe()#對於非數值型的資料,看看下面的結果obj = Series([‘c‘,‘a‘,‘a‘,‘b‘,‘d‘] * 4)print obj.describe()‘‘‘結果為:count 20unique 4top afreq 8其中,freq是指字母出現的最高頻率‘‘‘
#-*- encoding:utf-8 -*-import numpy as npimport osimport pandas as pdfrom pandas import Series,DataFrameimport matplotlib.pyplot as pltimport time#下面看一下cummin函數#注意:這裡的cummin函數是截止到目前為止的最小值,而不是加和以後的最小值frame = DataFrame([[1,2,3,4],[5,6,7,8],[-10,11,12,-13]],index = list(‘abc‘),columns = [‘one‘,‘two‘,‘three‘,‘four‘])print frame.cummin()print frame
>>>
one two three four
a 1 2 3 4
b 1 2 3 4
c -10 2 3 -13
one two three four
a 1 2 3 4
b 5 6 7 8
c -10 11 12 -13
相關係數與共變數
有些匯總統計(如相關係數和共變數)是通過參數對計算出來的。這一節資料得不到?上不去網。
唯一值、值計數以及成員資格
#-*- encoding:utf-8 -*-import numpy as npimport osimport pandas as pdfrom pandas import Series,DataFrameimport matplotlib.pyplot as pltobj = Series([‘a‘,‘a‘,‘b‘,‘f‘,‘e‘])uniques = obj.unique()uniques.sort() #記住這是就地排序#print uniques#下面進行計數統計,注意得到的是按照出現的頻率降序排列#print obj.value_counts()#value_counts還是一個頂級的pandas方法。可用於任何是數組或者序列#print obj.values#print pd.value_counts(obj.values,sort = False)#最後是isin 判斷向量化集合的成員資格,可用於選取Series中或DataF列中的子集mask = obj.isin([‘b‘,‘c‘])print maskprint obj[mask]data = DataFrame({‘Qu1‘:[1,3,4,3,4], ‘Qu2‘:[2,3,1,2,3], ‘Qu3‘:[1,5,2,4,4]})print dataprint data.apply(pd.value_counts).fillna(0)
上面這幾個函數是真的非常實用!
4、處理缺失資料
#-*- encoding:utf-8 -*-import numpy as npimport osimport pandas as pdfrom pandas import Series,DataFrameimport matplotlib.pyplot as pltimport timefrom numpy import nan as NA#pandas本來就被設計成自動忽略了缺失值、#nan None 都看做缺失值str_data = Series([‘a‘,np.nan,‘b‘,‘c‘])str_data[0] = Noneprint str_data.isnull()print str_data.notnull()
>>>
0 True
1 True
2 False
3 False
0 False
1 False
2 True
3 True
#NumPy的資料類型中缺少真正的NA資料類型或位元模式??
濾除缺失資料
#-*- encoding:utf-8 -*-import numpy as npimport osimport pandas as pdfrom pandas import Series,DataFrameimport matplotlib.pyplot as pltimport timefrom numpy import nan as NAdata = Series([1,NA,3.5,7,NA])#注意返回的是不為NA的值的原來的索引,不是移除之後的索引
#有一個函數 reset_index 這個函數(方法?)可以重新設定index,其中drop = True選項會丟棄原來的索引而設定新的從0開始的索引,這個方法只對DataFrame有用貌似。
print data.dropna()#下面的結果一樣print data[data.notnull()]data1 = DataFrame([[1,2,3],[NA,2.3,4],[NA,NA,NA]])#注意:由於DataFrame的設定,只要有NA的行就會捨棄print data1.dropna()#傳入how = ‘all‘ 則丟掉全為NA的行,這裡的 how 的起名真的有點隨心所欲了,哈哈print data1.dropna(how = ‘all‘)#丟棄列print data1.dropna(how = ‘all‘,axis = 1)#還有一個參數,threshdata2 = DataFrame(np.random.randn(7,3))data2.ix[:4,1] = NAdata2.ix[:2,2] = NA#print data2#這裡的thresh函數是選取最少non-NA值個數的行選出來print data2.dropna(thresh = 2)print data2.dropna(thresh = 4,axis = 1)
填充缺失資料
#-*- encoding:utf-8 -*-import numpy as npimport osimport pandas as pdfrom pandas import Series,DataFrameimport matplotlib.pyplot as pltimport timefrom numpy import nan as NA#主要用fillna方法填充NA處的值data2 = DataFrame(np.random.randn(7,3))data2.ix[:4,1] = NAdata2.ix[:2,2] = NA#fillna返回一個新對象,inplace = True 可以就地填充print data2.fillna(0)#print data2.fillna(0,inplace = True)#print data2#為不同的列填充要用到字典print data2.fillna({1:0.5,3:-1})#對reindex有效的那些差值方法也可適用於fillna,請向上看,或者搜尋 reindex 即可df = DataFrame(np.random.randn(6,3))df.ix[2:,1] = NAdf.ix[4:,2] = NAprint df.fillna(method = ‘ffill‘,limit = 2)#只要稍微動動腦子,我們就可以知道向NA處可以填充均值等其他數data = Series([1.2,NA,4,NA])print data.fillna(data.mean())
fillna的參數如下:
5、層次化索引
層次化索引(hierarchical index)是pandas的重要功能,這能使在一個軸上擁有兩個以上的索引層級。抽象點說,它能使你以低維度形式處理高維度。
#-*- encoding:utf-8 -*-import numpy as npimport osimport pandas as pdfrom pandas import Series,DataFrameimport matplotlib.pyplot as pltimport timedata = Series(np.random.randn(10),index=[[‘a‘,‘a‘,‘a‘,‘b‘,‘b‘,‘b‘,‘c‘,‘c‘,‘d‘,‘d‘],[1,2,3,1,2,3,1,2,2,3]])#print data#下面是索引的選取方式print data.indexprint data[‘b‘]print data[‘b‘:‘c‘]print data.ix[[‘b‘,‘d‘]]#下面是“內層”的選取方式print data[:,2]#層次化索引在資料重塑和基於分組操作(如透視表產生)中扮演者重要的角色,比如用unstack方式重排DataFrame:print data.unstack()#stack是unstack的逆運算print data.unstack().stack()#對於DataFrame,每個軸都可以有分層索引frame = DataFrame(np.arange(12).reshape((4,3)),index = [[‘a‘,‘a‘,‘b‘,‘b‘],[1,2,1,2]],columns = [[‘Ohio‘,‘Ohio‘,‘Colorado‘],[‘Green‘,‘Red‘,‘Green‘]])#print frame#注意下面的方式:是為每一個軸規定名字,跟frame.index.names = [‘key1‘,‘key2‘]frame.columns.names = [‘state‘,‘color‘]#print frame#print frame[‘Ohio‘]#可以單獨建立MultiIndex然後複用#下面的multiindex可以這樣建立,注意下面的產生方式columns = pd.MultiIndex.from_arrays([[‘Ohio‘,‘Ohio‘,‘Colorado‘],[‘Green‘,‘Red‘,‘Green‘]],names = [‘state‘,‘color‘])frame1 = DataFrame(np.arange(12).reshape((4,3)),columns = columns)print frame1#重排順序,調整索引層級print frame.swaplevel(‘key1‘,‘key2‘)#sortlevel則根據但各層級中的值對資料進行排序,通常用swaplevel是也會用到sortlevel(很合理)#注意得到的是副本,不是就地修改print frame.sortlevel(1)print frame.swaplevel(0,1).sortlevel(0)print frame#許多對DataFrame和Series進行描述匯總的統計都有一個level選項,用於指定匯總方式print frame.sum(level = ‘key2‘)#不指定level的話,會按照列匯總出所有列名的和print frame.sum()print frame.sum(level = ‘color‘,axis = 1)
#-*- encoding:utf-8 -*-import numpy as npimport osimport pandas as pdfrom pandas import Series,DataFrameimport matplotlib.pyplot as pltimport time#人們經常想將DataFrame的一個或者多個列當作行索引來用,或者可能需要將行索引變成DataFrame的列frame = DataFrame({‘a‘:range(7),‘b‘:range(7,0,-1),‘c‘:[‘one‘,‘one‘,‘one‘,‘two‘,‘two‘,‘two‘,‘two‘],‘d‘:[0,1,2,0,1,2,3]})print frame#DataFrame中的set_index函數會將其一個或者多個列轉換為行索引frame2 = frame.set_index([‘c‘,‘d‘])print frame2 #其實就是利用第3、4列進行一次分類匯總frame3 = frame.set_index([‘c‘,‘d‘],drop = False)#與set_index相反的是reset_index函數print frame2.reset_index()#下面進行一次測試frame4 = DataFrame([[0,7],[1,6],[2,5],[3,4],[4,3],[5,2],[6,1]],index = [[‘one‘,‘one‘,‘one‘,‘two‘,‘two‘,‘two‘,‘two‘],[0,1,2,0,1,2,3]],columns=[‘a‘,‘b‘])frame4.index.names = [‘c‘,‘d‘]print frame4print frame4.reset_index().sort_index(axis = 1)
其他有關pandas的話題
#-*- encoding:utf-8 -*-import numpy as npimport osimport pandas as pdfrom pandas import Series,DataFrameimport matplotlib.pyplot as pltimport pandas.io.data as web#這裡說的是一些蛋疼的問題:整數索引和整數標籤ser = Series(np.arange(3.))#print ser[-1] #報錯,因為整數索引的歧義性ser2 = Series(np.arange(3.),index = [‘a‘,‘b‘,‘c‘])print ser2[-1] #正確#ix函數總是面向標籤的print ser.ix[:1]#如果需要可靠的、不考慮索引類型的、基於位置的索引,可以使用Series的iget_value方法,Dataframe的irow 和 icol方法ser3 = Series(range(3),index= [-5,1,3])print ser3.iget_value(2)frame = DataFrame(np.arange(6).reshape(3,2),index = [2,0,1])print frame.irow(0)#pandas 有一個Panel資料結構(不是主要內容),可以看作是三維的DataFrame。pandas中的多維資料可以利用多層索引進行處理#可以利用DataFrame對象組成的字典或者一個三維ndarray來建立Panel對象pdata = pd.Panel(dict((stk,web.get_data_yahoo(stk,‘1/1/2009‘,‘6/1/2012‘)) for stk in [‘AAPL‘,‘GOOG‘,‘MSFT‘,‘DELL‘]))#網路錯誤,得不到資料#Panel的每一項都是一個DataFrame.
《利用python進行資料分析》讀書筆記--第五章 pandas入門