日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

Python 數(shù)據(jù)分析包:pandas 基礎(chǔ)

 劉對對 2017-01-01
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

 

Series


Series 可以看做一個定長的有序字典。基本任意的一維數(shù)據(jù)都可以用來構(gòu)造 Series 對象:

>>> s = Series([1,2,3.0,'abc'])>>> s0 11 22 33 abcdtype: object

雖然 dtype:object 可以包含多種基本數(shù)據(jù)類型,但總感覺會影響性能的樣子,最好還是保持單純的 dtype。

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 都含有一個 name 屬性:

>>> s.name = 'a_series'>>> s.index.name = 'the_index'>>> sthe_indexa 1b 3x 5y 7Name: a_series, dtype: int64

 

DataFrame


DataFrame 是一個表格型的數(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ù)為:DataFrame(data=None,index=None,coloumns=None),columns 即 “name”:

>>> 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 對象的重新索引通過其 .reindex(index=None,**kwargs) 方法實現(xiàn)。**kwargs 中常用的參數(shù)有倆:method=None,fill_value=np.NaN

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

.reindex() 方法會返回一個新對象,其 index 嚴(yán)格遵循給出的參數(shù),method:{'backfill', 'bfill', 'pad', 'ffill', None} 參數(shù)用于指定插值(填充)方式,當(dāng)沒有給出時,自動用 fill_value 填充,默認(rèn)為 NaN(ffill = pad,bfill = back fill,分別指插值時向前還是向后取值)

DataFrame 對象的重新索引方法為:.reindex(index=None,columns=None,**kwargs)。僅比 Series 多了一個可選的 columns 參數(shù),用于給列索引。用法與上例類似,只不過插值方法 method 參數(shù)只能應(yīng)用于,即軸 0。

>>> 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]

不過 fill_value 依然對有效。聰明的小伙伴可能已經(jīng)想到了,可不可以通過 df.T.reindex(index,method='**').T 這樣的方式來實現(xiàn)在列上的插值呢,答案是可行的。另外要注意,使用 reindex(index,method='**') 的時候,index 必須是單調(diào)的,否則就會引發(fā)一個 ValueError: Must be monotonic for forward fill,比如上例中的最后一次調(diào)用,如果使用 index=['a','b','d','c'] 的話就不行。

刪除指定軸上的項

即刪除 Series 的元素或 DataFrame 的某一行(列)的意思,通過對象的 .drop(labels, axis=0) 方法:

>>> 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]

.drop() 返回的是一個新對象,元對象不會被改變。

索引和切片

就像 Numpy,pandas 也支持通過 obj[::] 的方式進(jìn)行索引和切片,以及通過布爾型數(shù)組進(jìn)行過濾。

不過須要注意,因為 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)狀況相同;換成 'c' 這樣的字符串索引時,結(jié)果就包含了這個邊界元素。

另外一個特別之處在于 DataFrame 對象的索引方式,因為他有兩個軸向(雙重索引)。

可以這么理解:DataFrame 對象的標(biāo)準(zhǔn)切片語法為:.ix[::,::]。ix 對象可以接受兩套切片,分別為行(axis=0)和列(axis=1)的方向:

>>> 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 中提到過 fill_value 參數(shù),不過為了傳遞這個參數(shù),就需要使用對象的方法,而不是操作符:df1.add(df2,fill_value=0)。其他算術(shù)方法還有:sub(), div(), mul()。

Series 和 DataFrame 之間的算術(shù)運(yùn)算涉及廣播,暫時先不講。

函數(shù)應(yīng)用和映射

Numpy 的 ufuncs(元素級數(shù)組方法)也可用于操作 pandas 對象。

當(dāng)希望將函數(shù)應(yīng)用到 DataFrame 對象的某一行或列時,可以使用 .apply(func, axis=0, args=(), **kwds) 方法。

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 的 sort_index(ascending=True) 方法可以對 index 進(jìn)行排序操作,ascending 參數(shù)用于控制升序或降序,默認(rèn)為升序。

若要按值對 Series 進(jìn)行排序,當(dāng)使用 .order() 方法,任何缺失值默認(rèn)都會被放到 Series 的末尾。

在 DataFrame 上,.sort_index(axis=0, by=None, ascending=True) 方法多了一個軸向的選擇參數(shù)與一個 by 參數(shù),by 參數(shù)的作用是針對某一(些)進(jìn)行排序(不能對行使用 by 參數(shù)):

>>> 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]

排名(Series.rank(method='average', ascending=True))的作用與排序的不同之處在于,他會把對象的 values 替換成名次(從 1 到 n)。這時唯一的問題在于如何處理平級項,方法里的 method 參數(shù)就是起這個作用的,他有四個值可選:average, min, max, first。

>>> 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 的 .rank(axis=0, method='average', ascending=True) 方法多了個 axis 參數(shù),可選擇按行或列分別進(jìn)行排名,暫時好像沒有針對全部元素的排名方法。

統(tǒng)計方法

pandas 對象有一些統(tǒng)計方法。它們大部分都屬于約簡和匯總統(tǒng)計,用于從 Series 中提取單個值,或從 DataFrame 的行或列中提取一個 Series。

比如 DataFrame.mean(axis=0,skipna=True) 方法,當(dāng)數(shù)據(jù)集中存在 NA 值時,這些值會被簡單跳過,除非整個切片(行或列)全是 NA,如果不想這樣,則可以通過 skipna=False 來禁用此功能:

>>> 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)計方法有:

########################******************************************
count非 NA 值的數(shù)量
describe針對 Series 或 DF 的列計算匯總統(tǒng)計
min , max最小值和最大值
argmin , argmax最小值和最大值的索引位置(整數(shù))
idxmin , idxmax最小值和最大值的索引值
quantile樣本分位數(shù)(0 到 1)
sum求和
mean均值
median中位數(shù)
mad根據(jù)均值計算平均絕對離差
var方差
std標(biāo)準(zhǔn)差
skew樣本值的偏度(三階矩)
kurt樣本值的峰度(四階矩)
cumsum樣本值的累計和
cummin , cummax樣本值的累計最大值和累計最小值
cumprod樣本值的累計積
diff計算一階差分(對時間序列很有用)
pct_change計算百分?jǐn)?shù)變化

 

處理缺失數(shù)據(jù)


pandas 中 NA 的主要表現(xiàn)為 np.nan,另外 Python 內(nèi)建的 None 也會被當(dāng)做 NA 處理。

處理 NA 的方法有四種:dropna , fillna , isnull , notnull

is(not)null

這一對方法對對象做元素級應(yīng)用,然后返回一個布爾型數(shù)組,一般可用于布爾型索引。

dropna

對于一個 Series,dropna 返回一個僅含非空數(shù)據(jù)和索引值的 Series。

問題在于對 DataFrame 的處理方式,因為一旦 drop 的話,至少要丟掉一行(列)。這里的解決方式與前面類似,還是通過一個額外的參數(shù):dropna(axis=0, how='any', thresh=None) ,how 參數(shù)可選的值為 any 或者 all。all 僅在切片元素全為 NA 時才拋棄該行(列)。另外一個有趣的參數(shù)是 thresh,該參數(shù)的類型為整數(shù),它的作用是,比如 thresh=3,會在一行中至少有 3 個非 NA 值時將其保留。

fillna

fillna(value=None, method=None, axis=0) 中的 value 參數(shù)除了基本類型外,還可以使用字典,這樣可以實現(xiàn)對不同的列填充不同的值。method 的用法與前面 .reindex() 方法相同,這里不再贅述。

inplace 參數(shù)


前面有個點一直沒講,結(jié)果整篇示例寫下來發(fā)現(xiàn)還挺重要的。就是 Series 和 DataFrame 對象的方法中,凡是會對數(shù)組作出修改并返回一個新數(shù)組的,往往都有一個 replace=False 的可選參數(shù)。如果手動設(shè)定為 True,那么原數(shù)組就可以被替換。

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多