數(shù)據(jù)的取值與選擇
series 數(shù)據(jù)選擇方式
- 1、將series看做字典
# 1、將series看做字典
data = pd.Series([0.25,0.5,0.75,1],index = ['a','b','c','d'])
data['c']
## 判斷鍵a 是否存在
'a' in data
# 獲取所有的鍵
data.keys()
##調(diào)用items()方法
list(data.items())
## 動(dòng)態(tài)的添加數(shù)據(jù)
data['e'] = 1.25
data
-
2、將series當(dāng)做一維數(shù)組
【解釋】:series 擁有和Numpy數(shù)組一樣的功能,包括:索引、切片、掩碼、花哨索引
【注意】:顯示索引選擇時(shí),包括最后一個(gè)索引。隱式索引則不包括。
索引器
索引器包括:loc、iloc、ix
| 函數(shù) | 說明 |
|---|---|
| .loc() | 基于標(biāo)簽,參數(shù)可為單個(gè)標(biāo)簽、標(biāo)簽列表、切片對象或者布爾數(shù)組 |
| .iloc() | 基于索引,參數(shù)可為整數(shù)、整數(shù)列表、系列值 |
data = pd.Series(['a','b','c'],index=[1,4,6])
data
[Out]:
1 a
4 b
6 c
dtype: object
- loc:表示使用顯示索引
data.loc[1]
[Out]:'a'
data.loc[1:3]
---
[Out]:1 a
dtype: object
- iloc :表示隱式索引
data.iloc[1]
data.iloc[1:3]
[Out]:
4 b
6 c
dtype: object
DataFrame 數(shù)據(jù)選擇方式
population_dict={'Californis':345987634,'New York':40768934,'Florida':76543212,'Illinois':156898456}
area_dict= {'Californis':336784,'New York':4908874,'Florida':43212,'Illinois':12986}
pop = pd.Series(population_dict)
area = pd.Series(area_dict)
data = pd.DataFrame({'area':area,'pop':pop})
data
[Out]:
area pop
Californis 336784 345987634
New York 4908874 40768934
Florida 43212 76543212
Illinois 12986 156898456
-
將DataFrame 看做字典
DataFrame- 字典
- 將DataFrame看做二維數(shù)組
1、按行查看數(shù)組數(shù)據(jù)
-
2、轉(zhuǎn)置操作
DataFrame-二維數(shù)組 3、用索引器來取值

【技能提升】:ix 索引器,可以將顯示索引和隱式索引混合使用。但是 ix不被新版本支持了,所以作為了解就好。
data.ix[:'Florida',:2]
---【警告】:
<pre style="box-sizing: border-box; overflow: auto; font-family: monospace; font-size: 14px; display: block; padding: 1px 0px; margin: 0px; line-height: inherit; color: rgb(0, 0, 0); word-break: break-all; overflow-wrap: break-word; background-color: transparent; border: 0px; border-radius: 0px; white-space: pre-wrap; vertical-align: baseline; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">C:\Users\admin\Anaconda3\lib\site-packages\ipykernel_launcher.py:2: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
[http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated](http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated)</pre>
【】:
任何處于處理Numpy形式數(shù)據(jù)的方法 ,都可以用于這些索引器。比如:掩碼、花式索引;

【】:任何一種取值方法,都可以用于調(diào)整數(shù)據(jù)。

其他的一些選值操作

【解釋】:
- 對單個(gè)標(biāo)簽取值,選擇的是列;
- 對多個(gè)標(biāo)簽用切片操作取值,選擇的是行;
- 【隱式索引編號】:切片也可以直接用行數(shù)實(shí)現(xiàn);
- 【掩碼操作】:可以直接對一行過濾
Pandas 的數(shù)值運(yùn)算方法
通用函數(shù):保留索引

通用函數(shù):對齊索引
area = pd.Series({'Californis':336784,'Florida':43212,'Illinois':12986})
population = pd.Series({'Californis':345987634,'New York':40768934,'Illinois':156898456})
population / area
[Out]:
Californis 1027.328003
Florida NaN
Illinois 12082.123518
New York NaN
dtype: float64
【解釋】:
- NaN:表示“此處沒有數(shù)據(jù)”;
- 任何缺失值都會(huì)用NaN來填充;
- 如果NaN不是我們想要的數(shù)據(jù)結(jié)果,可以用通用函數(shù)的fill_value來設(shè)定
- DataFrame在計(jì)算時(shí),也會(huì)在列上索引對齊,并且計(jì)算結(jié)果會(huì)對索引自動(dòng)排序;
使用fill_value 來填充缺失值:

DataFrame 和Series的運(yùn)算

【注釋】:
- 通過axis參數(shù),可以指定計(jì)算的方式
- DataFrame 和Series 運(yùn)算時(shí),結(jié)果的索引也會(huì)自動(dòng)對齊;
df -df.iloc[0]
---[Out]:
Q E S T
0 0 0 0 0
1 -1 -2 0 7
2 -9 -1 -1 2
df.subtract(df['E'],axis=0) # (按列計(jì)算)
---[Out]:
Q E S T
0 1 0 0 -8
1 2 0 2 1
2 -7 0 0 -5
halfrow = df.iloc[0,::22]
halfrow
---[Out]:
Q 9
Name: 0, dtype: int32
缺失值處理
Pandas 采用標(biāo)簽法來表示缺失值,有兩種方式:
- 浮點(diǎn)數(shù)據(jù)類型的NaN值;
- pyton對象類型:None;
【備注】: - Python對象類型的缺失值,只能用于Numpy; Pandas:中的‘objects’類型數(shù)據(jù);
- object 類型數(shù)據(jù)會(huì)消耗更多的資源;

【注意】:
- 無法對包含None的數(shù)組進(jìn)行累計(jì)操作;(例如:
vals1.sum()) - NaN:數(shù)值類型的缺失值;
- 任何數(shù)字與NaN進(jìn)行運(yùn)算,結(jié)果都是NaN;
-【例外】:Numpy中 提供了忽視Nan缺失值影響的函數(shù)(nansum、nanmax、nanmin);

Pandas 中None與NaN的比較
pandas 將None與NaN看成是可等價(jià)交換的,在適當(dāng)?shù)臅r(shí)候,會(huì)將兩者進(jìn)行替換,除此之外,Pandas 會(huì)將沒有標(biāo)簽值的數(shù)據(jù),自動(dòng)轉(zhuǎn)換成NaN。實(shí)例如下:
pd.Series([1,np.nan,2,None])
輸出:
0 1.0
1 NaN
2 2.0
3 NaN
dtype: float64
x[0] = None
x
輸出:
0 NaN
1 1.0
dtype: float64
andas:對不同類型的缺失值的轉(zhuǎn)換規(guī)則
| 類型 | 缺失值 | NaN標(biāo)簽值 |
|---|---|---|
| floating(浮點(diǎn)型) | 無變化 | np.nan |
| object(對象類型) | 無變化 | None,Np.nan |
| iteger(整數(shù)類型) | 強(qiáng)制轉(zhuǎn)換為float64 | np.nan |
| boolean(布爾型) | 強(qiáng)制轉(zhuǎn)換為object | None或者np.nan |
【注意】:Pandas 中,字符串使用object類型存儲(chǔ)。
缺失值處理
| 函數(shù) | 說明 |
|---|---|
| isnull() | 如果為NA,返回布爾值True,否則為False |
| notnull() | 與isnull()相反 |
| fillna() | 尋找NA值,替換為value,參數(shù)method填充方式:pad/ffill向前填充,bfill/backfill向后填充 |
| ffill() | 等同于fillna(method=’ffill’) |
| bfill() | 等同于fillna(method=’bfill’) |
| dropna() | 丟棄包含NA值的行或者列,axis默認(rèn)為0,即丟棄行 |
| replace() | 替換,用標(biāo)量值替換NA則等同于 fillna()函數(shù) |
data = pd.Series([1, np.nan,'hello',None])
### 創(chuàng)建一個(gè)布爾類型的掩碼標(biāo)簽缺失值;;
data.isnull()
"""輸出
0 False
1 True
2 False
3 True
dtype: bool
"""
# 與isnull 操作相反
data.notnull()
"""輸出
0 True
1 False
2 True
3 False
dtype: bool
"""
# 返會(huì)一個(gè)除去缺失值的數(shù)據(jù)
data.dropna()
"""輸出
0 1
2 hello
dtype: object
"""
df = pd.DataFrame([[1,np.nan,2],[2,3,5],[np.nan,4,6]])
df
"""輸出
0 1 2
0 1.0 NaN 2
1 2.0 3.0 5
2 NaN 4.0 6
"""
#默認(rèn)刪除包含缺失值的正行數(shù)據(jù)
df.dropna()
"""輸出
0 1 2
1 2.0 3.0 5
"""
# 刪除包含缺失值的整列數(shù)據(jù)
df.dropna(axis=1)
"""輸出
2
0 2
1 5
2 6
"""
df[3] = np.nan
df
"""輸出
0 1 2 3
0 1.0 NaN 2 NaN
1 2.0 3.0 5 NaN
2 NaN 4.0 6 NaN
"""
# 只有全部是缺失數(shù)據(jù)才刪除;
df.dropna(axis = 1,how = 'all')
"""輸出
0 1 2
0 1.0 NaN 2
1 2.0 3.0 5
2 NaN 4.0 6
"""
# 【thresh】
df.dropna(axis=1,thresh=3)
"""輸出
2
0 2
1 5
2 6
"""
關(guān)于 【thresh】:通過thresh 設(shè)置非缺失值的最小數(shù)量(thresh=n:表沒有缺失值)
填充缺失值:fillna
- 使用0填充缺失值;
- 用缺失值前面的有效值來填充缺失值。
- 用缺失值后面的有效值來填充缺失值。

【備注】:# DataFrame 填充方法與Series相似,但是填充時(shí),需要設(shè)定坐標(biāo)軸參數(shù):axis
例如:
df.fillna(method='ffill',axis=1)
層級索引
index = [('California',2000),('California',2020),('New York',2000),('New York',2020),('Texas',2000),('Texas',2020),]
populations=[3564549,3965987,1984654,2484654,1566432,3564895]
pop = pd.Series(populations,index=index)
pop
"""輸出
(California, 2000) 3564549
(California, 2020) 3965987
(New York, 2000) 1984654
(New York, 2020) 2484654
(Texas, 2000) 1566432
(Texas, 2020) 3564895
dtype: int64
"""
## 查出2000年所有州的數(shù)據(jù)
pop[[i for i in pop.index if i[1]==2000]]
"""輸出
(California, 2000) 3564549
(New York, 2000) 1984654
(Texas, 2000) 1566432
dtype: int64
"""
【方法優(yōu)化】:
- Pandas 多級索引;
- 通過元組的列表創(chuàng)建多級索引;
index = pd.MultiIndex.from_tuples(index)
index
"""輸出
MultiIndex(levels=[['California', 'New York', 'Texas'], [2000, 2020]],
labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]])
"""
pop = pop.reindex(index)
pop
"""輸出
California 2000 3564549
2020 3965987
New York 2000 1984654
2020 2484654
Texas 2000 1566432
2020 3564895
dtype: int64
"""
## 選取2020年的所有數(shù)據(jù)
pop[:,2020]
"""輸出
California 3965987
New York 2484654
Texas 3564895
dtype: int64
"""
高級數(shù)據(jù)的多級索引
- unstack() : 可以講一個(gè)擁有多級索引的Series轉(zhuǎn)換為普通索引的DataFrame;
- stack() : 可以將普通索引的DataFrame轉(zhuǎn)換為擁有多級索引的Series
pop_df = pop.unstack()
pop_df
"""輸出
2000 2020
California 3564549 3965987
New York 1984654 2484654
Texas 1566432 3564895
"""
# stack() : 可以將普通索引的DataFrame轉(zhuǎn)換為擁有多級索引的Series
pop_df.stack()
"""輸出
California 2000 3564549
2020 3965987
New York 2000 1984654
2020 2484654
Texas 2000 1566432
2020 3564895
dtype: int64
"""

創(chuàng)建多級索引
將Series | DataFrame 的index參數(shù)設(shè)置為至少二維的索引數(shù)組
df = pd.DataFrame(np.random.rand(4,2),index=[['a','a','b','b'],[1,2,1,2]],columns=['data1','data2'])
df
"""輸出
data1 data2
a 1 0.800254 0.222281
2 0.352115 0.467182
b 1 0.982438 0.396324
2 0.313206 0.891846
"""
data = {
('California',2000):3564549,
('California',2020):3965987,
('Texas',2000):1984654,
('Texas',2020):2484654,
('New York',2000):1566432,
('New York',2020):3564895
}
pd.Series(data)
"""輸出
California 2000 3564549
2020 3965987
Texas 2000 1984654
2020 2484654
New York 2000 1566432
2020 3564895
dtype: int64
"""



