国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
Python 數(shù)據(jù)分析包:pandas 基礎(chǔ)
閱讀目錄
重新索引
刪除指定軸上的項(xiàng)
索引和切片
算術(shù)運(yùn)算和數(shù)據(jù)對(duì)齊
函數(shù)應(yīng)用和映射
排序和排名
統(tǒng)計(jì)方法
is(not)null
dropna
fillna
pandas 是基于 Numpy 構(gòu)建的含有更高級(jí)數(shù)據(jù)結(jié)構(gòu)和工具的數(shù)據(jù)分析包類似于 Numpy 的核心是 ndarray,pandas 也是圍繞著 Series 和 DataFrame 兩個(gè)核心數(shù)據(jù)結(jié)構(gòu)展開的 。Series 和 DataFrame 分別對(duì)應(yīng)于一維的序列和二維的表結(jié)構(gòu)。pandas 約定俗成的導(dǎo)入方法如下:
1
2
from pandas import Series,DataFrame
import pandas as pd
Series
Series 可以看做一個(gè)定長的有序字典。基本任意的一維數(shù)據(jù)都可以用來構(gòu)造 Series 對(duì)象:
1
2
3
4
5
6
7
>>> s = Series([1,2,3.0,'abc'])
>>> s
0      1
1      2
2      3
3    abc
dtype: object
雖然 dtype:object 可以包含多種基本數(shù)據(jù)類型,但總感覺會(huì)影響性能的樣子,最好還是保持單純的 dtype。
Series 對(duì)象包含兩個(gè)主要的屬性:index 和 values,分別為上例中左右兩列。因?yàn)閭鹘o構(gòu)造器的是一個(gè)列表,所以 index 的值是從 0 起遞增的整數(shù),如果傳入的是一個(gè)類字典的鍵值對(duì)結(jié)構(gòu),就會(huì)生成 index-value 對(duì)應(yīng)的 Series;或者在初始化的時(shí)候以關(guān)鍵字參數(shù)顯式指定一個(gè) index 對(duì)象:
1
2
3
4
5
6
7
8
9
10
11
>>> s = Series(data=[1,3,5,7],index = ['a','b','x','y'])
>>> s
a    1
b    3
x    5
y    7
dtype: int64
>>> s.index
Index(['a', 'b', 'x', 'y'], dtype='object')
>>> s.values
array([1, 3, 5, 7], dtype=int64)
Series 對(duì)象的元素會(huì)嚴(yán)格依照給出的 index 構(gòu)建,這意味著:如果 data 參數(shù)是有鍵值對(duì)的,那么只有 index 中含有的鍵會(huì)被使用;以及如果 data 中缺少響應(yīng)的鍵,即使給出 NaN 值,這個(gè)鍵也會(huì)被添加。
注意 Series 的 index 和 values 的元素之間雖然存在對(duì)應(yīng)關(guān)系,但這與字典的映射不同。index 和 values 實(shí)際仍為互相獨(dú)立的 ndarray 數(shù)組,因此 Series 對(duì)象的性能完全 ok。
Series 這種使用鍵值對(duì)的數(shù)據(jù)結(jié)構(gòu)最大的好處在于,Series 間進(jìn)行算術(shù)運(yùn)算時(shí),index 會(huì)自動(dòng)對(duì)齊。
另外,Series 對(duì)象和它的 index 都含有一個(gè) name 屬性:
1
2
3
4
5
6
7
8
9
>>> s.name = 'a_series'
>>> s.index.name = 'the_index'
>>> s
the_index
a            1
b            3
x            5
y            7
Name: a_series, dtype: int64
DataFrame
DataFrame 是一個(gè)表格型的數(shù)據(jù)結(jié)構(gòu),它含有一組有序的列(類似于 index),每列可以是不同的值類型(不像 ndarray 只能有一個(gè) dtype)?;旧峡梢园?DataFrame 看成是共享同一個(gè) index 的 Series 的集合。
DataFrame 的構(gòu)造方法與 Series 類似,只不過可以同時(shí)接受多條一維數(shù)據(jù)源,每一條都會(huì)成為單獨(dú)的一列:
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> 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  year
0  1.5   Ohino  2000
1  1.7   Ohino  2001
2  3.6   Ohino  2002
3  2.4  Nevada  2001
4  2.9  Nevada  2002
[5 rows x 3 columns]
雖然參數(shù) data 看起來是個(gè)字典,但字典的鍵并非充當(dāng) DataFrame 的 index 的角色,而是 Series 的 “name” 屬性。這里生成的 index 仍是 “01234”。
較完整的 DataFrame 構(gòu)造器參數(shù)為:DataFrame(data=None,index=None,coloumns=None),columns 即 “name”:
1
2
3
4
5
6
7
8
9
10
11
>>> df = DataFrame(data,index=['one','two','three','four','five'],
columns=['year','state','pop','debt'])
>>> df
year   state  pop debt
one    2000   Ohino  1.5  NaN
two    2001   Ohino  1.7  NaN
three  2002   Ohino  3.6  NaN
four   2001  Nevada  2.4  NaN
five   2002  Nevada  2.9  NaN
[5 rows x 4 columns]
同樣缺失值由 NaN 補(bǔ)上。看一下 index、columns 和 索引的類型:
1
2
3
4
5
6
>>> df.index
Index(['one', 'two', 'three', 'four', 'five'], dtype='object')
>>> df.columns
Index(['year', 'state', 'pop', 'debt'], dtype='object')
>>> type(df['debt'])
<class 'pandas.core.series.Series'>
DataFrame 面向行和面向列的操作基本是平衡的,任意抽出一列都是 Series。
對(duì)象屬性
重新索引
Series 對(duì)象的重新索引通過其 .reindex(index=None,**kwargs) 方法實(shí)現(xiàn)。**kwargs 中常用的參數(shù)有倆:method=None,fill_value=np.NaN:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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.3
b    7.2
c    3.6
d    4.5
e    NaN
dtype: float64
>>> ser.reindex(a,fill_value=0)
a   -5.3
b    7.2
c    3.6
d    4.5
e    0.0
dtype: float64
>>> ser.reindex(a,method='ffill')
a   -5.3
b    7.2
c    3.6
d    4.5
e    4.5
dtype: float64
>>> ser.reindex(a,fill_value=0,method='ffill')
a   -5.3
b    7.2
c    3.6
d    4.5
e    4.5
dtype: float64
.reindex() 方法會(huì)返回一個(gè)新對(duì)象,其 index 嚴(yán)格遵循給出的參數(shù),method:{'backfill', 'bfill', 'pad', 'ffill', None} 參數(shù)用于指定插值(填充)方式,當(dāng)沒有給出時(shí),自動(dòng)用fill_value 填充,默認(rèn)為 NaN(ffill = pad,bfill = back fill,分別指插值時(shí)向前還是向后取值)
DataFrame 對(duì)象的重新索引方法為:.reindex(index=None,columns=None,**kwargs)。僅比 Series 多了一個(gè)可選的 columns 參數(shù),用于給列索引。用法與上例類似,只不過插值方法 method 參數(shù)只能應(yīng)用于行,即軸 0。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> state = ['Texas','Utha','California']
>>> df.reindex(columns=state,method='ffill')
Texas  Utha  California
a      1   NaN           2
c      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  California
a      1   NaN           2
b      1   NaN           2
c      4   NaN           5
d      7   NaN           8
[4 rows x 3 columns]
不過 fill_value 依然對(duì)有效。聰明的小伙伴可能已經(jīng)想到了,可不可以通過 df.T.reindex(index,method='**').T 這樣的方式來實(shí)現(xiàn)在列上的插值呢,答案是可行的。另外要注意,使用 reindex(index,method='**') 的時(shí)候,index 必須是單調(diào)的,否則就會(huì)引發(fā)一個(gè) ValueError: Must be monotonic for forward fill,比如上例中的最后一次調(diào)用,如果使用 index=['a','b','d','c'] 的話就不行。
回到頂部
刪除指定軸上的項(xiàng)
即刪除 Series 的元素或 DataFrame 的某一行(列)的意思,通過對(duì)象的 .drop(labels, axis=0) 方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
>>> ser
d    4.5
b    7.2
a   -5.3
c    3.6
dtype: float64
>>> df
Ohio  Texas  California
a     0      1           2
c     3      4           5
d     6      7           8
[3 rows x 3 columns]
>>> ser.drop('c')
d    4.5
b    7.2
a   -5.3
dtype: float64
>>> df.drop('a')
Ohio  Texas  California
c     3      4           5
d     6      7           8
[2 rows x 3 columns]
>>> df.drop(['Ohio','Texas'],axis=1)
California
a           2
c           5
d           8
[3 rows x 1 columns]
.drop() 返回的是一個(gè)新對(duì)象,元對(duì)象不會(huì)被改變。
回到頂部
索引和切片
就像 Numpy,pandas 也支持通過 obj[::] 的方式進(jìn)行索引和切片,以及通過布爾型數(shù)組進(jìn)行過濾。
不過須要注意,因?yàn)?pandas 對(duì)象的 index 不限于整數(shù),所以當(dāng)使用非整數(shù)作為切片索引時(shí),它是末端包含的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
>>> foo
a    4.5
b    7.2
c   -5.3
d    3.6
dtype: float64
>>> bar
0    4.5
1    7.2
2   -5.3
3    3.6
dtype: float64
>>> foo[:2]
a    4.5
b    7.2
dtype: float64
>>> bar[:2]
0    4.5
1    7.2
dtype: float64
>>> foo[:'c']
a    4.5
b    7.2
c   -5.3
dtype: float64
這里 foo 和 bar 只有 index 不同——bar 的 index 是整數(shù)序列??梢姰?dāng)使用整數(shù)索引切片時(shí),結(jié)果與 Python 列表或 Numpy 的默認(rèn)狀況相同;換成 'c' 這樣的字符串索引時(shí),結(jié)果就包含了這個(gè)邊界元素。
另外一個(gè)特別之處在于 DataFrame 對(duì)象的索引方式,因?yàn)樗袃蓚€(gè)軸向(雙重索引)。
可以這么理解:DataFrame 對(duì)象的標(biāo)準(zhǔn)切片語法為:.ix[::,::]。ix 對(duì)象可以接受兩套切片,分別為行(axis=0)和列(axis=1)的方向:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> df
Ohio  Texas  California
a     0      1           2
c     3      4           5
d     6      7           8
[3 rows x 3 columns]
>>> df.ix[:2,:2]
Ohio  Texas
a     0      1
c     3      4
[2 rows x 2 columns]
>>> df.ix['a','Ohio']
0
而不使用 ix ,直接切的情況就特殊了:
索引時(shí),選取的是列
切片時(shí),選取的是行
這看起來有點(diǎn)不合邏輯,但作者解釋說 “這種語法設(shè)定來源于實(shí)踐”,我們信他。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> df['Ohio']
a    0
c    3
d    6
Name: Ohio, dtype: int32
>>> df[:'c']
Ohio  Texas  California
a     0      1           2
c     3      4           5
[2 rows x 3 columns]
>>> df[:2]
Ohio  Texas  California
a     0      1           2
c     3      4           5
[2 rows x 3 columns]
使用布爾型數(shù)組的情況,注意行與列的不同切法(列切法的 : 不能?。?div style="height:15px;">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> df['Texas']>=4
a    False
c     True
d     True
Name: Texas, dtype: bool
>>> df[df['Texas']>=4]
Ohio  Texas  California
c     3      4           5
d     6      7           8
[2 rows x 3 columns]
>>> df.ix[:,df.ix['c']>=4]
Texas  California
a      1           2
c      4           5
d      7           8
[3 rows x 2 columns]
回到頂部
算術(shù)運(yùn)算和數(shù)據(jù)對(duì)齊
pandas 最重要的一個(gè)功能是,它可以對(duì)不同索引的對(duì)象進(jìn)行算術(shù)運(yùn)算。在將對(duì)象相加時(shí),結(jié)果的索引取索引對(duì)的并集。自動(dòng)的數(shù)據(jù)對(duì)齊在不重疊的索引處引入空值,默認(rèn)為 NaN。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> foo = Series({'a':1,'b':2})
>>> foo
a    1
b    2
dtype: int64
>>> bar = Series({'b':3,'d':4})
>>> bar
b    3
d    4
dtype: int64
>>> foo + bar
a   NaN
b     5
d   NaN
dtype: float64
DataFrame 的對(duì)齊操作會(huì)同時(shí)發(fā)生在行和列上。
當(dāng)不希望在運(yùn)算結(jié)果中出現(xiàn) NA 值時(shí),可以使用前面 reindex 中提到過 fill_value 參數(shù),不過為了傳遞這個(gè)參數(shù),就需要使用對(duì)象的方法,而不是操作符:df1.add(df2,fill_value=0)。其他算術(shù)方法還有:sub(), div(), mul()。
Series 和 DataFrame 之間的算術(shù)運(yùn)算涉及廣播,暫時(shí)先不講。
回到頂部
函數(shù)應(yīng)用和映射
Numpy 的 ufuncs(元素級(jí)數(shù)組方法)也可用于操作 pandas 對(duì)象。
當(dāng)希望將函數(shù)應(yīng)用到 DataFrame 對(duì)象的某一行或列時(shí),可以使用 .apply(func, axis=0, args=(), **kwds) 方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
f = lambda x:x.max()-x.min()
>>> df
Ohio  Texas  California
a     0      1           2
c     3      4           5
d     6      7           8
[3 rows x 3 columns]
>>> df.apply(f)
Ohio          6
Texas         6
California    6
dtype: int64
>>> df.apply(f,axis=1)
a    2
c    2
d    2
dtype: int64
回到頂部
排序和排名
Series 的 sort_index(ascending=True) 方法可以對(duì) index 進(jìn)行排序操作,ascending 參數(shù)用于控制升序或降序,默認(rèn)為升序。
若要按值對(duì) Series 進(jìn)行排序,當(dāng)使用 .order() 方法,任何缺失值默認(rèn)都會(huì)被放到 Series 的末尾。
在 DataFrame 上,.sort_index(axis=0, by=None, ascending=True) 方法多了一個(gè)軸向的選擇參數(shù)與一個(gè) by 參數(shù),by 參數(shù)的作用是針對(duì)某一(些)列進(jìn)行排序(不能對(duì)行使用 by 參數(shù)):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> df.sort_index(by='Ohio')
Ohio  Texas  California
a     0      1           2
c     3      4           5
d     6      7           8
[3 rows x 3 columns]
>>> df.sort_index(by=['California','Texas'])
Ohio  Texas  California
a     0      1           2
c     3      4           5
d     6      7           8
[3 rows x 3 columns]
>>> df.sort_index(axis=1)
California  Ohio  Texas
a           2     0      1
c           5     3      4
d           8     6      7
[3 rows x 3 columns]
排名(Series.rank(method='average', ascending=True))的作用與排序的不同之處在于,他會(huì)把對(duì)象的 values 替換成名次(從 1 到 n)。這時(shí)唯一的問題在于如何處理平級(jí)項(xiàng),方法里的 method 參數(shù)就是起這個(gè)作用的,他有四個(gè)值可選:average, min, max, first。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
>>> ser=Series([3,2,0,3],index=list('abcd'))
>>> ser
a    3
b    2
c    0
d    3
dtype: int64
>>> ser.rank()
a    3.5
b    2.0
c    1.0
d    3.5
dtype: float64
>>> ser.rank(method='min')
a    3
b    2
c    1
d    3
dtype: float64
>>> ser.rank(method='max')
a    4
b    2
c    1
d    4
dtype: float64
>>> ser.rank(method='first')
a    3
b    2
c    1
d    4
dtype: float64
注意在 ser[0]=ser[3] 這對(duì)平級(jí)項(xiàng)上,不同 method 參數(shù)表現(xiàn)出的不同名次。
DataFrame 的 .rank(axis=0, method='average', ascending=True) 方法多了個(gè) axis 參數(shù),可選擇按行或列分別進(jìn)行排名,暫時(shí)好像沒有針對(duì)全部元素的排名方法。
回到頂部
統(tǒng)計(jì)方法
pandas 對(duì)象有一些統(tǒng)計(jì)方法。它們大部分都屬于約簡和匯總統(tǒng)計(jì),用于從 Series 中提取單個(gè)值,或從 DataFrame 的行或列中提取一個(gè) Series。
比如 DataFrame.mean(axis=0,skipna=True) 方法,當(dāng)數(shù)據(jù)集中存在 NA 值時(shí),這些值會(huì)被簡單跳過,除非整個(gè)切片(行或列)全是 NA,如果不想這樣,則可以通過 skipna=False 來禁用此功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>>> df
one  two
a  1.40  NaN
b  7.10 -4.5
c   NaN  NaN
d  0.75 -1.3
[4 rows x 2 columns]
>>> df.mean()
one    3.083333
two   -2.900000
dtype: float64
>>> df.mean(axis=1)
a    1.400
b    1.300
c      NaN
d   -0.275
dtype: float64
>>> df.mean(axis=1,skipna=False)
a      NaN
b    1.300
c      NaN
d   -0.275
dtype: float64
其他常用的統(tǒng)計(jì)方法有:
########################******************************************
count非 NA 值的數(shù)量
describe針對(duì) Series 或 DF 的列計(jì)算匯總統(tǒng)計(jì)
min , max最小值和最大值
argmin , argmax最小值和最大值的索引位置(整數(shù))
idxmin , idxmax最小值和最大值的索引值
quantile樣本分位數(shù)(0 到 1)
sum求和
mean均值
median中位數(shù)
mad根據(jù)均值計(jì)算平均絕對(duì)離差
var方差
std標(biāo)準(zhǔn)差
skew樣本值的偏度(三階矩)
kurt樣本值的峰度(四階矩)
cumsum樣本值的累計(jì)和
cummin , cummax樣本值的累計(jì)最大值和累計(jì)最小值
cumprod樣本值的累計(jì)積
diff計(jì)算一階差分(對(duì)時(shí)間序列很有用)
pct_change計(jì)算百分?jǐn)?shù)變化
處理缺失數(shù)據(jù)
pandas 中 NA 的主要表現(xiàn)為 np.nan,另外 Python 內(nèi)建的 None 也會(huì)被當(dāng)做 NA 處理。
處理 NA 的方法有四種:dropna , fillna , isnull , notnull 。
回到頂部
is(not)null
這一對(duì)方法對(duì)對(duì)象做元素級(jí)應(yīng)用,然后返回一個(gè)布爾型數(shù)組,一般可用于布爾型索引。
回到頂部
dropna
對(duì)于一個(gè) Series,dropna 返回一個(gè)僅含非空數(shù)據(jù)和索引值的 Series。
問題在于對(duì) DataFrame 的處理方式,因?yàn)橐坏?drop 的話,至少要丟掉一行(列)。這里的解決方式與前面類似,還是通過一個(gè)額外的參數(shù):dropna(axis=0, how='any', thresh=None) ,how 參數(shù)可選的值為 any 或者 all。all 僅在切片元素全為 NA 時(shí)才拋棄該行(列)。另外一個(gè)有趣的參數(shù)是 thresh,該參數(shù)的類型為整數(shù),它的作用是,比如 thresh=3,會(huì)在一行中至少有 3 個(gè)非 NA 值時(shí)將其保留。
回到頂部
fillna
fillna(value=None, method=None, axis=0) 中的 value 參數(shù)除了基本類型外,還可以使用字典,這樣可以實(shí)現(xiàn)對(duì)不同的列填充不同的值。method 的用法與前面 .reindex() 方法相同,這里不再贅述。
inplace 參數(shù)
前面有個(gè)點(diǎn)一直沒講,結(jié)果整篇示例寫下來發(fā)現(xiàn)還挺重要的。就是 Series 和 DataFrame 對(duì)象的方法中,凡是會(huì)對(duì)數(shù)組作出修改并返回一個(gè)新數(shù)組的,往往都有一個(gè) replace=False 的可選參數(shù)。如果手動(dòng)設(shè)定為 True,那么原數(shù)組就可以被替換。
轉(zhuǎn)載:http://www.open-open.com/lib/view/open1402477162868.html
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
利用Python進(jìn)行數(shù)據(jù)分析
簡約而不簡單|值得收藏的Pandas基本操作指南
<font style="vertical-align: inherit;"><font style="vertical-align: inherit;
[轉(zhuǎn)]10 minutes to pandas
小白也能看懂的Pandas實(shí)操演示教程(下)
pandas小記:pandas索引和選擇
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服