pandas 是基于 Numpy 構(gòu)建的含有更高級數(shù)據(jù)結(jié)構(gòu)和工具的數(shù)據(jù)分析包 類似于 Numpy 的核心是 ndarray,pandas 也是圍繞著 Series 和 DataFrame 兩個核心數(shù)據(jù)結(jié)構(gòu)展開的 。Series 和 DataFrame 分別對應(yīng)于一維的序列和二維的表結(jié)構(gòu)。pandas 約定俗成的導(dǎo)入方法如下: from pandas import Series,DataFrameimport pandas as pd
SeriesSeries 可以看做一個定長的有序字典。基本任意的一維數(shù)據(jù)都可以用來構(gòu)造 Series 對象: >>> s = Series([1,2,3.0,'abc'])>>> s0 11 22 33 abcdtype: object 雖然 Series 對象包含兩個主要的屬性:index 和 values,分別為上例中左右兩列。因為傳給構(gòu)造器的是一個列表,所以 index 的值是從 0 起遞增的整數(shù),如果傳入的是一個類字典的鍵值對結(jié)構(gòu),就會生成 index-value 對應(yīng)的 Series;或者在初始化的時候以關(guān)鍵字參數(shù)顯式指定一個 index 對象: >>> s = Series(data=[1,3,5,7],index = ['a','b','x','y'])>>> sa 1b 3x 5y 7dtype: int64>>> s.indexIndex(['a', 'b', 'x', 'y'], dtype='object')>>> s.valuesarray([1, 3, 5, 7], dtype=int64) Series 對象的元素會嚴(yán)格依照給出的 index 構(gòu)建,這意味著:如果 data 參數(shù)是有鍵值對的,那么只有 index 中含有的鍵會被使用;以及如果 data 中缺少響應(yīng)的鍵,即使給出 NaN 值,這個鍵也會被添加。 注意 Series 的 index 和 values 的元素之間雖然存在對應(yīng)關(guān)系,但這與字典的映射不同。index 和 values 實際仍為互相獨立的 ndarray 數(shù)組,因此 Series 對象的性能完全 ok。 Series 這種使用鍵值對的數(shù)據(jù)結(jié)構(gòu)最大的好處在于,Series 間進(jìn)行算術(shù)運(yùn)算時,index 會自動對齊。 另外,Series 對象和它的 index 都含有一個 >>> s.name = 'a_series'>>> s.index.name = 'the_index'>>> sthe_indexa 1b 3x 5y 7Name: a_series, dtype: int64
DataFrameDataFrame 是一個表格型的數(shù)據(jù)結(jié)構(gòu),它含有一組有序的列(類似于 index),每列可以是不同的值類型(不像 ndarray 只能有一個 dtype)?;旧峡梢园?DataFrame 看成是共享同一個 index 的 Series 的集合。 DataFrame 的構(gòu)造方法與 Series 類似,只不過可以同時接受多條一維數(shù)據(jù)源,每一條都會成為單獨的一列: >>> data = {'state':['Ohino','Ohino','Ohino','Nevada','Nevada'], 'year':[2000,2001,2002,2001,2002], 'pop':[1.5,1.7,3.6,2.4,2.9]}>>> df = DataFrame(data)>>> df pop state year0 1.5 Ohino 20001 1.7 Ohino 20012 3.6 Ohino 20023 2.4 Nevada 20014 2.9 Nevada 2002[5 rows x 3 columns] 雖然參數(shù) data 看起來是個字典,但字典的鍵并非充當(dāng) DataFrame 的 index 的角色,而是 Series 的 “name” 屬性。這里生成的 index 仍是 “01234”。 較完整的 DataFrame 構(gòu)造器參數(shù)為: >>> df = DataFrame(data,index=['one','two','three','four','five'], columns=['year','state','pop','debt'])>>> df year state pop debtone 2000 Ohino 1.5 NaNtwo 2001 Ohino 1.7 NaNthree 2002 Ohino 3.6 NaNfour 2001 Nevada 2.4 NaNfive 2002 Nevada 2.9 NaN[5 rows x 4 columns] 同樣缺失值由 NaN 補(bǔ)上??匆幌?index、columns 和 索引的類型: >>> df.indexIndex(['one', 'two', 'three', 'four', 'five'], dtype='object')>>> df.columnsIndex(['year', 'state', 'pop', 'debt'], dtype='object')>>> type(df['debt'])<class 'pandas.core.series.Series'> DataFrame 面向行和面向列的操作基本是平衡的,任意抽出一列都是 Series。 對象屬性重新索引Series 對象的重新索引通過其 ser = Series([4.5,7.2,-5.3,3.6],index=['d','b','a','c'])>>> a = ['a','b','c','d','e']>>> ser.reindex(a)a -5.3b 7.2c 3.6d 4.5e NaNdtype: float64>>> ser.reindex(a,fill_value=0)a -5.3b 7.2c 3.6d 4.5e 0.0dtype: float64>>> ser.reindex(a,method='ffill')a -5.3b 7.2c 3.6d 4.5e 4.5dtype: float64>>> ser.reindex(a,fill_value=0,method='ffill')a -5.3b 7.2c 3.6d 4.5e 4.5dtype: float64
DataFrame 對象的重新索引方法為: >>> state = ['Texas','Utha','California']>>> df.reindex(columns=state,method='ffill') Texas Utha Californiaa 1 NaN 2c 4 NaN 5 d 7 NaN 8[3 rows x 3 columns]>>> df.reindex(index=['a','b','c','d'],columns=state,method='ffill') Texas Utha Californiaa 1 NaN 2b 1 NaN 2c 4 NaN 5d 7 NaN 8[4 rows x 3 columns] 不過 刪除指定軸上的項即刪除 Series 的元素或 DataFrame 的某一行(列)的意思,通過對象的 >>> serd 4.5b 7.2a -5.3c 3.6dtype: float64>>> df Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8[3 rows x 3 columns]>>> ser.drop('c')d 4.5b 7.2a -5.3dtype: float64>>> df.drop('a') Ohio Texas Californiac 3 4 5d 6 7 8[2 rows x 3 columns]>>> df.drop(['Ohio','Texas'],axis=1) Californiaa 2c 5d 8[3 rows x 1 columns]
索引和切片就像 Numpy,pandas 也支持通過 不過須要注意,因為 pandas 對象的 index 不限于整數(shù),所以當(dāng)使用非整數(shù)作為切片索引時,它是末端包含的。 >>> fooa 4.5b 7.2c -5.3d 3.6dtype: float64>>> bar0 4.51 7.22 -5.33 3.6dtype: float64>>> foo[:2]a 4.5b 7.2dtype: float64>>> bar[:2]0 4.51 7.2dtype: float64>>> foo[:'c']a 4.5b 7.2c -5.3dtype: float64 這里 foo 和 bar 只有 index 不同——bar 的 index 是整數(shù)序列??梢姰?dāng)使用整數(shù)索引切片時,結(jié)果與 Python 列表或 Numpy 的默認(rèn)狀況相同;換成 另外一個特別之處在于 DataFrame 對象的索引方式,因為他有兩個軸向(雙重索引)。 可以這么理解:DataFrame 對象的標(biāo)準(zhǔn)切片語法為: >>> df Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8[3 rows x 3 columns]>>> df.ix[:2,:2] Ohio Texasa 0 1c 3 4[2 rows x 2 columns]>>> df.ix['a','Ohio']0 而不使用 ix ,直接切的情況就特殊了:
這看起來有點不合邏輯,但作者解釋說 “這種語法設(shè)定來源于實踐”,我們信他。 >>> df['Ohio']a 0c 3d 6Name: Ohio, dtype: int32>>> df[:'c'] Ohio Texas Californiaa 0 1 2c 3 4 5[2 rows x 3 columns]>>> df[:2] Ohio Texas Californiaa 0 1 2c 3 4 5[2 rows x 3 columns] 使用布爾型數(shù)組的情況,注意行與列的不同切法(列切法的 >>> df['Texas']>=4a Falsec Trued TrueName: Texas, dtype: bool>>> df[df['Texas']>=4] Ohio Texas Californiac 3 4 5d 6 7 8[2 rows x 3 columns]>>> df.ix[:,df.ix['c']>=4] Texas Californiaa 1 2c 4 5d 7 8[3 rows x 2 columns]
算術(shù)運(yùn)算和數(shù)據(jù)對齊pandas 最重要的一個功能是,它可以對不同索引的對象進(jìn)行算術(shù)運(yùn)算。在將對象相加時,結(jié)果的索引取索引對的并集。自動的數(shù)據(jù)對齊在不重疊的索引處引入空值,默認(rèn)為 NaN。 >>> foo = Series({'a':1,'b':2})>>> fooa 1b 2dtype: int64>>> bar = Series({'b':3,'d':4})>>> barb 3d 4dtype: int64>>> foo + bara NaNb 5d NaNdtype: float64 DataFrame 的對齊操作會同時發(fā)生在行和列上。 當(dāng)不希望在運(yùn)算結(jié)果中出現(xiàn) NA 值時,可以使用前面 reindex 中提到過 Series 和 DataFrame 之間的算術(shù)運(yùn)算涉及廣播,暫時先不講。 函數(shù)應(yīng)用和映射Numpy 的 ufuncs(元素級數(shù)組方法)也可用于操作 pandas 對象。 當(dāng)希望將函數(shù)應(yīng)用到 DataFrame 對象的某一行或列時,可以使用 f = lambda x:x.max()-x.min()>>> df Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8[3 rows x 3 columns]>>> df.apply(f)Ohio 6Texas 6California 6dtype: int64>>> df.apply(f,axis=1)a 2c 2d 2dtype: int64
排序和排名Series 的 若要按值對 Series 進(jìn)行排序,當(dāng)使用 在 DataFrame 上, >>> df.sort_index(by='Ohio') Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8[3 rows x 3 columns]>>> df.sort_index(by=['California','Texas']) Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8[3 rows x 3 columns]>>> df.sort_index(axis=1) California Ohio Texasa 2 0 1c 5 3 4d 8 6 7[3 rows x 3 columns] 排名( >>> ser=Series([3,2,0,3],index=list('abcd'))>>> sera 3b 2c 0d 3dtype: int64>>> ser.rank()a 3.5b 2.0c 1.0d 3.5dtype: float64>>> ser.rank(method='min')a 3b 2c 1d 3dtype: float64>>> ser.rank(method='max')a 4b 2c 1d 4dtype: float64>>> ser.rank(method='first')a 3b 2c 1d 4dtype: float64 注意在 ser[0]=ser[3] 這對平級項上,不同 method 參數(shù)表現(xiàn)出的不同名次。 DataFrame 的 統(tǒng)計方法pandas 對象有一些統(tǒng)計方法。它們大部分都屬于約簡和匯總統(tǒng)計,用于從 Series 中提取單個值,或從 DataFrame 的行或列中提取一個 Series。 比如 >>> df one twoa 1.40 NaNb 7.10 -4.5c NaN NaNd 0.75 -1.3[4 rows x 2 columns]>>> df.mean()one 3.083333two -2.900000dtype: float64>>> df.mean(axis=1)a 1.400b 1.300c NaNd -0.275dtype: float64>>> df.mean(axis=1,skipna=False)a NaNb 1.300c NaNd -0.275dtype: float64 其他常用的統(tǒng)計方法有:
處理缺失數(shù)據(jù)pandas 中 NA 的主要表現(xiàn)為 np.nan,另外 Python 內(nèi)建的 None 也會被當(dāng)做 NA 處理。 處理 NA 的方法有四種: is(not)null這一對方法對對象做元素級應(yīng)用,然后返回一個布爾型數(shù)組,一般可用于布爾型索引。 dropna對于一個 Series,dropna 返回一個僅含非空數(shù)據(jù)和索引值的 Series。 問題在于對 DataFrame 的處理方式,因為一旦 drop 的話,至少要丟掉一行(列)。這里的解決方式與前面類似,還是通過一個額外的參數(shù): fillna
inplace 參數(shù)前面有個點一直沒講,結(jié)果整篇示例寫下來發(fā)現(xiàn)還挺重要的。就是 Series 和 DataFrame 對象的方法中,凡是會對數(shù)組作出修改并返回一個新數(shù)組的,往往都有一個 |
|