關(guān)于《利用python進(jìn)行數(shù)據(jù)分析》和原博文http://www.itdecent.cn/p/ac7bec000dad的個人學(xué)習(xí)筆記
源代碼https://github.com/wesm/pydata-book/blob/2nd-edition/ch07.ipynb
討論處理缺失數(shù)據(jù)、重復(fù)數(shù)據(jù)、字符串操作和其它分析數(shù)據(jù)轉(zhuǎn)換
處理缺失數(shù)據(jù)
判斷缺失數(shù)據(jù)
- 對于數(shù)值數(shù)據(jù),pandas使用浮點(diǎn)值NaN(Not a Number)表示缺失數(shù)據(jù)
- Python內(nèi)置的None值在對象數(shù)組中也可以作為NA
- 在pandas中,將缺失值表示為NA,表示不可用not available。
In [12]: string_data.isnull()
Out[12]:
0 False
1 False
2 True
3 False
dtype: bool
表列出了一些關(guān)于缺失數(shù)據(jù)處理的函數(shù)。

過濾缺失數(shù)據(jù)
- 過濾掉缺失數(shù)據(jù)可以通過pandas.isnull或布爾索引
- 對于一個Series,dropna返回一個僅含非空數(shù)據(jù)和索引值的Series
In [15]: from numpy import nan as NA
In [16]: data = pd.Series([1, NA, 3.5, NA, 7])
In [17]: data.dropna()
Out[17]:
0 1.0
2 3.5
4 7.0
dtype: float64
In [18]: data[data.notnull()]
Out[18]:
0 1.0
2 3.5
4 7.0
dtype: float64
- 對于DataFrame對象可能希望丟棄全NA或含有NA的行或列
- dropna默認(rèn)丟棄任何含有缺失值的行
- 傳入how='all'將只丟棄全為NA的那些行
- 用這種方式丟棄列,只需傳入axis=1
- 只想留下一部分觀測數(shù)據(jù)可以用thresh參數(shù),一行除去NA值,剩余數(shù)值的數(shù)量大于等于n,便顯示這一行
In [20]: cleaned = data.dropna()
In [21]: data
Out[21]:
0 1 2
0 1.0 6.5 3.0
1 1.0 NaN NaN
2 NaN NaN NaN
3 NaN 6.5 3.0
In [22]: cleaned
Out[22]:
0 1 2
0 1.0 6.5 3.0
In [23]: data.dropna(how='all')
Out[23]:
0 1 2
0 1.0 6.5 3.0
1 1.0 NaN NaN
3 NaN 6.5 3.0
In [25]: data
Out[25]:
0 1 2 4
0 1.0 6.5 3.0 NaN
1 1.0 NaN NaN NaN
2 NaN NaN NaN NaN
3 NaN 6.5 3.0 NaN
In [26]: data.dropna(axis=1, how='all')
Out[26]:
0 1 2
0 1.0 6.5 3.0
1 1.0 NaN NaN
2 NaN NaN NaN
3 NaN 6.5 3.0
In [30]: df
Out[30]:
0 1 2
0 -0.204708 NaN NaN
1 -0.555730 NaN NaN
2 0.092908 NaN 0.769023
3 1.246435 NaN -1.296221
4 0.274992 0.228913 1.352917
5 0.886429 -2.001637 -0.371843
6 1.669025 -0.438570 -0.539741
In [32]: df.dropna(thresh=2)
Out[32]:
0 1 2
2 0.092908 NaN 0.769023
3 1.246435 NaN -1.296221
4 0.274992 0.228913 1.352917
5 0.886429 -2.001637 -0.371843
6 1.669025 -0.438570 -0.539741
填充缺失數(shù)據(jù)
- 一個常數(shù)調(diào)用fillna就會將缺失值替換為那個常數(shù)值
In [33]: df.fillna(0)
Out[33]:
0 1 2
0 -0.204708 0.000000 0.000000
1 -0.555730 0.000000 0.000000
2 0.092908 0.000000 0.769023
3 1.246435 0.000000 -1.296221
4 0.274992 0.228913 1.352917
- 通過一個字典調(diào)用fillna可以實(shí)現(xiàn)對不同的列填充不同的值
In [34]: df.fillna({1: 0.5, 2: 0})
Out[34]:
0 1 2
0 -0.204708 0.500000 0.000000
1 -0.555730 0.500000 0.000000
2 0.092908 0.500000 0.769023
3 1.246435 0.500000 -1.296221
4 0.274992 0.228913 1.352917
- fillna默認(rèn)會返回新對象,也可以對現(xiàn)有對象就地修改
In [35]: _ = df.fillna(0, inplace=True)
In [36]: df
Out[36]:
0 1 2
0 -0.204708 0.000000 0.000000
1 -0.555730 0.000000 0.000000
2 0.092908 0.000000 0.769023
3 1.246435 0.000000 -1.296221
4 0.274992 0.228913 1.352917
5 0.886429 -2.001637 -0.371843
6 1.669025 -0.438570 -0.539741
- 對reindexing有效的那些插值方法也可用于fillna
In [40]: df
Out[40]:
0 1 2
0 0.476985 3.248944 -1.021228
1 -0.577087 0.124121 0.302614
2 0.523772 NaN 1.343810
3 -0.713544 NaN -2.370232
4 -1.860761 NaN NaN
5 -1.265934 NaN NaN
In [41]: df.fillna(method='ffill')
Out[41]:
0 1 2
0 0.476985 3.248944 -1.021228
1 -0.577087 0.124121 0.302614
2 0.523772 0.124121 1.343810
3 -0.713544 0.124121 -2.370232
4 -1.860761 0.124121 -2.370232
5 -1.265934 0.124121 -2.370232
In [42]: df.fillna(method='ffill', limit=2)
Out[42]:
0 1 2
0 0.476985 3.248944 -1.021228
1 -0.577087 0.124121 0.302614
2 0.523772 0.124121 1.343810
3 -0.713544 0.124121 -2.370232
4 -1.860761 NaN -2.370232
5 -1.265934 NaN -2.370232
- 可以傳入Series的平均值或中位數(shù)
In [44]: data.fillna(data.mean())
Out[44]:
0 1.000000
1 3.833333
2 3.500000
3 3.833333
4 7.000000
dtype: float64
表7-2列出了fillna的參考。


數(shù)據(jù)轉(zhuǎn)換
移除重復(fù)數(shù)據(jù)
- DataFrame的duplicated方法返回一個布爾型Series,表示各行是否是重復(fù)行(前面出現(xiàn)過的行)
In [46]: data
Out[46]:
k1 k2
0 one 1
1 two 1
2 one 2
3 two 3
4 one 3
5 two 4
6 two 4
In [47]: data.duplicated()
Out[47]:
0 False
1 False
2 False
3 False
4 False
5 False
6 True
dtype: bool
- drop_duplicates方法會返回一個DataFrame,刪除重復(fù)
In [48]: data.drop_duplicates()
Out[48]:
k1 k2
0 one 1
1 two 1
2 one 2
3 two 3
4 one 3
5 two 4
- 方法默認(rèn)會判斷全部列,也可以指定部分列進(jìn)行重復(fù)項(xiàng)判斷
In [49]: data['v1'] = range(7)
In [50]: data.drop_duplicates(['k1'])
Out[50]:
k1 k2 v1
0 one 1 0
1 two 1 1
- 默認(rèn)保留的是第一個出現(xiàn)的值組合,keep='last'則保留最后一個
利用函數(shù)或映射進(jìn)行數(shù)據(jù)轉(zhuǎn)換
添加一列表示該肉類食物來源的動物類型,先編寫一個不同肉類到動物的映射
In [53]: data
Out[53]:
food ounces
0 bacon 4.0
1 pulled pork 3.0
2 bacon 12.0
3 Pastrami 6.0
4 corned beef 7.5
5 Bacon 8.0
6 pastrami 3.0
7 honey ham 5.0
8 nova lox 6.0
meat_to_animal = {
'bacon': 'pig',
'pulled pork': 'pig',
'pastrami': 'cow',
'corned beef': 'cow',
'honey ham': 'pig',
'nova lox': 'salmon'
}
使用Series的str.lower方法,將各個值轉(zhuǎn)換為小寫
Series的map方法可以接受一個函數(shù)或含有映射關(guān)系的字典型對象
In [55]: lowercased = data['food'].str.lower()
In [56]: lowercased
Out[56]:
0 bacon
1 pulled pork
2 bacon
3 pastrami
4 corned beef
5 bacon
6 pastrami
7 honey ham
8 nova lox
Name: food, dtype: object
In [57]: data['animal'] = lowercased.map(meat_to_animal)
In [58]: data
Out[58]:
food ounces animal
0 bacon 4.0 pig
1 pulled pork 3.0 pig
2 bacon 12.0 pig
3 Pastrami 6.0 cow
4 corned beef 7.5 cow
5 Bacon 8.0 pig
6 pastrami 3.0 cow
7 honey ham 5.0 pig
8 nova lox 6.0 salmon
可以傳入一個能夠完成全部這些工作的函數(shù):
In [59]: data['food'].map(lambda x: meat_to_animal[x.lower()])
Out[59]:
0 pig
1 pig
2 pig
3 cow
4 cow
5 pig
6 cow
7 pig
8 salmon
Name: food, dtype: object
替換值
利用fillna方法填充缺失數(shù)據(jù)可以看做值替換的一種特殊情況。map可用于修改對象的數(shù)據(jù)子集,replace實(shí)現(xiàn)該功能更簡單靈活
-999這個值是表示缺失數(shù)據(jù)的標(biāo)記值,利用replace來產(chǎn)生一個新的Series(除非傳入inplace=True)
In [61]: data
Out[61]:
0 1.0
1 -999.0
2 2.0
3 -999.0
4 -1000.0
5 3.0
In [62]: data.replace(-999, np.nan)
Out[62]:
0 1.0
1 NaN
2 2.0
3 NaN
4 -1000.0
5 3.0
dtype: float64
一次性替換多個值可以傳入一個由待替換值組成的列表以及一個替換值
In [63]: data.replace([-999, -1000], np.nan)
Out[63]:
0 1.0
1 NaN
2 2.0
3 NaN
4 NaN
5 3.0
dtype: float64
要讓每個值有不同的替換值,可以傳遞一個替換列表或字典
In [64]: data.replace([-999, -1000], [np.nan, 0])
Out[64]:
0 1.0
1 NaN
2 2.0
3 NaN
4 0.0
5 3.0
dtype: float64
In [65]: data.replace({-999: np.nan, -1000: 0})
Out[65]:
0 1.0
1 NaN
2 2.0
3 NaN
4 0.0
5 3.0
dtype: float64
data.replace方法與data.str.replace不同,后者做的是字符串的元素級替換
重命名軸索引
跟Series中的值一樣,軸標(biāo)簽也可以通過函數(shù)或映射進(jìn)行轉(zhuǎn)換,得到一個新的不同標(biāo)簽的對象。
將其賦值給index,這樣就可以對DataFrame進(jìn)行就地修改
In [66]: data = pd.DataFrame(np.arange(12).reshape((3, 4)),
....: index=['Ohio', 'Colorado', 'New York'],
....: columns=['one', 'two', 'three', 'four'])
In [67]: transform = lambda x: x[:4].upper()
In [68]: data.index.map(transform)
Out[68]: Index(['OHIO', 'COLO', 'NEW '], dtype='object')
In [69]: data.index = data.index.map(transform)
In [70]: data
Out[70]:
one two three four
OHIO 0 1 2 3
COLO 4 5 6 7
NEW 8 9 10 11
創(chuàng)建數(shù)據(jù)集的轉(zhuǎn)換版(而不是修改原始數(shù)據(jù)),比較實(shí)用的方法是rename
In [71]: data.rename(index=str.title, columns=str.upper)
Out[71]:
ONE TWO THREE FOUR
Ohio 0 1 2 3
Colo 4 5 6 7
New 8 9 10 11
rename可以結(jié)合字典型對象實(shí)現(xiàn)對部分軸標(biāo)簽的更新,就地修改某個數(shù)據(jù)集,傳入inplace=True即可
In [72]: data.rename(index={'OHIO': 'INDIANA'},
....: columns={'three': 'peekaboo'})
Out[72]:
one two peekaboo four
INDIANA 0 1 2 3
COLO 4 5 6 7
NEW 8 9 10 11
離散化和面元劃分
為了便于分析,連續(xù)數(shù)據(jù)常常被離散化或拆分為“面元”(bin)
假設(shè)有一組人員數(shù)據(jù),劃分為“18到25”、“26到35”、“35到60”以及“60以上”幾個面元,使用pandas的cut函數(shù)
In [75]: ages = [20, 22, 25, 27, 21, 23, 37, 31, 61, 45, 41, 32]
In [76]: bins = [18, 25, 35, 60, 100]
In [77]: cats = pd.cut(ages, bins)
In [78]: cats
Out[78]:
[(18, 25], (18, 25], (18, 25], (25, 35], (18, 25], ..., (25, 35], (60, 100], (35,60], (35, 60], (25, 35]]
Length: 12
Categories (4, interval[int64]): [(18, 25] < (25, 35] < (35, 60] < (60, 100]]
pandas返回的是一個特殊的Categorical對象,展示了pandas.cut劃分的面元。可以將其看做一組表示面元名稱的字符串。它的底層含有一個表示不同分類名稱的類型數(shù)組,以及一個codes屬性中的年齡數(shù)據(jù)的標(biāo)簽
pd.value_counts(cats)是pandas.cut結(jié)果的面元計數(shù)
In [79]: cats.codes
Out[79]: array([0, 0, 0, 1, 0, 0, 2, 1, 3, 2, 2, 1], dtype=int8)
In [80]: cats.categories
Out[80]:
IntervalIndex([(18, 25], (25, 35], (35, 60], (60, 100]]
closed='right',
dtype='interval[int64]')
In [81]: pd.value_counts(cats)
Out[81]:
(18, 25] 5
(35, 60] 3
(25, 35] 3
(60, 100] 1
dtype: int64
閉端可以通過right=False進(jìn)行修改
In [82]: pd.cut(ages, [18, 26, 36, 61, 100], right=False)
Out[82]:
[[18, 26), [18, 26), [18, 26), [26, 36), [18, 26), ..., [26, 36), [61, 100), [36,
61), [36, 61), [26, 36)]
Length: 12
Categories (4, interval[int64]): [[18, 26) < [26, 36) < [36, 61) < [61, 100)]
通過傳遞一個列表或數(shù)組到labels設(shè)置自己的面元名稱
In [83]: group_names = ['Youth', 'YoungAdult', 'MiddleAged', 'Senior']
In [84]: pd.cut(ages, bins, labels=group_names)
Out[84]:
[Youth, Youth, Youth, YoungAdult, Youth, ..., YoungAdult, Senior, MiddleAged, Mid
dleAged, YoungAdult]
Length: 12
Categories (4, object): [Youth < YoungAdult < MiddleAged < Senior]
如果向cut傳入的是面元的數(shù)量而不是確切的面元邊界,則會根據(jù)數(shù)據(jù)的最小值和最大值計算等長面元
選項(xiàng)precision=2,限定小數(shù)只有兩位
In [86]: pd.cut(data, 4, precision=2)
Out[86]:
[(0.34, 0.55], (0.34, 0.55], (0.76, 0.97], (0.76, 0.97], (0.34, 0.55], ..., (0.34
, 0.55], (0.34, 0.55], (0.55, 0.76], (0.34, 0.55], (0.12, 0.34]]
Length: 20
Categories (4, interval[float64]): [(0.12, 0.34] < (0.34, 0.55] < (0.55, 0.76] <
(0.76, 0.97]]
qcut是一個類似cut的函數(shù),可以根據(jù)樣本分位數(shù)對數(shù)據(jù)進(jìn)行面元劃分。根據(jù)數(shù)據(jù)的分布情況,cut可能無法使各個面元中含有相同數(shù)量的數(shù)據(jù)點(diǎn)。而qcut由于使用的是樣本分位數(shù),因此可以得到大小基本相等的面元:
In [87]: data = np.random.randn(1000) # Normally distributed
In [88]: cats = pd.qcut(data, 4) # Cut into quartiles
In [89]: cats
Out[89]:
[(-0.0265, 0.62], (0.62, 3.928], (-0.68, -0.0265], (0.62, 3.928], (-0.0265, 0.62]
, ..., (-0.68, -0.0265], (-0.68, -0.0265], (-2.95, -0.68], (0.62, 3.928], (-0.68,
-0.0265]]
Length: 1000
Categories (4, interval[float64]): [(-2.95, -0.68] < (-0.68, -0.0265] < (-0.0265,
0.62] <
(0.62, 3.928]]
In [90]: pd.value_counts(cats)
Out[90]:
(0.62, 3.928] 250
(-0.0265, 0.62] 250
(-0.68, -0.0265] 250
(-2.95, -0.68] 250
dtype: int64
與cut類似,你也可以傳遞自定義的分位數(shù)(0到1之間的數(shù)值,包含端點(diǎn)):
In [91]: pd.qcut(data, [0, 0.1, 0.5, 0.9, 1.])
Out[91]:
[(-0.0265, 1.286], (-0.0265, 1.286], (-1.187, -0.0265], (-0.0265, 1.286], (-0.026
5, 1.286], ..., (-1.187, -0.0265], (-1.187, -0.0265], (-2.95, -1.187], (-0.0265,
1.286], (-1.187, -0.0265]]
Length: 1000
Categories (4, interval[float64]): [(-2.95, -1.187] < (-1.187, -0.0265] < (-0.026
5, 1.286] <
(1.286, 3.928]]
檢測和過濾異常值
過濾或變換異常值(outlier)就是運(yùn)用數(shù)組運(yùn)算
要找出某列中絕對值大小超過3的值
In [92]: data = pd.DataFrame(np.random.randn(100
0, 4))
In [93]: data.describe()
Out[93]:
0 1 2 3
count 1000.000000 1000.000000 1000.000000 1000.000000
mean 0.049091 0.026112 -0.002544 -0.051827
std 0.996947 1.007458 0.995232 0.998311
min -3.645860 -3.184377 -3.745356 -3.428254
25% -0.599807 -0.612162 -0.687373 -0.747478
50% 0.047101 -0.013609 -0.022158 -0.088274
75% 0.756646 0.695298 0.699046 0.623331
max 2.653656 3.525865 2.735527 3.366626
In [94]: col = data[2]
In [95]: col[np.abs(col) > 3]
Out[95]:
41 -3.399312
136 -3.745356
Name: 2, dtype: float64
要選出全部含有“超過3或-3的值”的行,在布爾型DataFrame中使用any方法
In [96]: data[(np.abs(data) > 3).any(1)]
Out[96]:
0 1 2 3
41 0.457246 -0.025907 -3.399312 -0.974657
60 1.951312 3.260383 0.963301 1.201206
136 0.508391 -0.196713 -3.745356 -1.520113
235 -0.242459 -3.056990 1.918403 -0.578828
258 0.682841 0.326045 0.425384 -3.428254
322 1.179227 -3.184377 1.369891 -1.074833
544 -3.548824 1.553205 -2.186301 1.277104
635 -0.578093 0.193299 1.397822 3.366626
782 -0.207434 3.525865 0.283070 0.544635
803 -3.645860 0.255475 -0.549574 -1.907459
將值限制在區(qū)間-3到3以內(nèi)
根據(jù)數(shù)據(jù)的值是正還是負(fù),np.sign(data)可以生成1和-1
In [97]: data[np.abs(data) > 3] = np.sign(data) * 3
In [98]: data.describe()
Out[98]:
0 1 2 3
count 1000.000000 1000.000000 1000.000000 1000.000000
mean 0.050286 0.025567 -0.001399 -0.051765
std 0.992920 1.004214 0.991414 0.995761
min -3.000000 -3.000000 -3.000000 -3.000000
25% -0.599807 -0.612162 -0.687373 -0.747478
50% 0.047101 -0.013609 -0.022158 -0.088274
75% 0.756646 0.695298 0.699046 0.623331
max 2.653656 3.000000 2.735527 3.000000
排列和隨機(jī)采樣
排列
- 利用np.random.permutation函數(shù)對Series或DataFrame的列排列隨機(jī)重排序
- 通過排列軸的長度調(diào)用permutation,產(chǎn)生一個表示新順序的整數(shù)數(shù)組
In [100]: df = pd.DataFrame(np.arange(5 * 4).reshape((5, 4)))
In [103]: df
Out[103]:
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
4 16 17 18 19
In [101]: sampler = np.random.permutation(5)
# 列長度為5
In [102]: sampler
Out[102]: array([3, 1, 4, 2, 0])# 產(chǎn)生一個表示新順序的整數(shù)數(shù)組
- iloc的索引操作或take函數(shù)中使用該數(shù)組
In [104]: df.take(sampler)
Out[104]:
0 1 2 3
3 12 13 14 15
1 4 5 6 7
4 16 17 18 19
2 8 9 10 11
0 0 1 2 3
隨機(jī)抽樣
- 不用替換的方式選取隨機(jī)子集(不允許重復(fù)),可以使用sample方法
- 替換的方式產(chǎn)生樣本(允許重復(fù)選擇),可以傳遞replace=True
In [105]: df.sample(n=3)# 選擇不同的行
Out[105]:
0 1 2 3
3 12 13 14 15
4 16 17 18 19
2 8 9 10 11
計算指標(biāo)/啞變量
將分類變量(categorical variable)轉(zhuǎn)換為“啞變量”或“指標(biāo)矩陣”
- DataFrame的某一列中含有k個不同的值
- get_dummies函數(shù)可以派生出一個k列矩陣或DataFrame(其值全為1和0)
In [109]: df = pd.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'],
.....: 'data1': range(6)})
In [110]: pd.get_dummies(df['key'])# dummy復(fù)數(shù)
Out[110]:
a b c
0 0 1 0
1 0 1 0
2 1 0 0
3 0 0 1
4 1 0 0
5 0 1 0
- prefix參數(shù)可以給指標(biāo)DataFrame的列加上一個前綴,以便能夠跟其他數(shù)據(jù)進(jìn)行合并
In [111]: dummies = pd.get_dummies(df['key'], prefix='key')
In [112]: df_with_dummy = df[['data1']].join(dummies)
In [113]: df_with_dummy
Out[113]:
data1 key_a key_b key_c
0 0 0 1 0
1 1 0 1 0
2 2 1 0 0
3 3 0 0 1
4 4 1 0 0
5 5 0 1 0
如果DataFrame中的某行同屬于多個分類,要為每個genre添加指標(biāo)變量就需要做一些數(shù)據(jù)規(guī)整操作
In [116]: movies[:10]
Out[116]:
movie_id title genres
0 1 Toy Story (1995) Animation|Children's|Comedy
1 2 Jumanji (1995) Adventure|Children's|Fantasy
2 3 Grumpier Old Men (1995) Comedy|Romance
3 4 Waiting to Exhale (1995) Comedy|Drama
4 5 Father of the Bride Part II (1995) Comedy
5 6 Heat (1995) Action|Crime|Thriller
6 7 Sabrina (1995) Comedy|Romance
7 8 Tom and Huck (1995) Adventure|Children's
8 9 Sudden Death (1995)
Action
9 10 GoldenEye (1995) Action|Adventure|Thriller
- 從數(shù)據(jù)集中抽取出不同的genre值
In [117]: all_genres = []
In [118]: for x in movies.genres:
.....: all_genres.extend(x.split('|'))
In [119]: genres = pd.unique(all_genres)
In [120]: genres
Out[120]:
array(['Animation', "Children's", 'Comedy', 'Adventure', 'Fantasy',
'Romance', 'Drama', 'Action', 'Crime', 'Thriller','Horror',
'Sci-Fi', 'Documentary', 'War', 'Musical', 'Mystery', 'Film-Noir',
'Western'], dtype=object)
- 構(gòu)建一個全零DataFrame
In [121]: zero_matrix = np.zeros((len(movies), len(genres)))
In [122]: dummies = pd.DataFrame(zero_matrix, columns=genres)
- 迭代每一行,使用dummies.columns來計算每個類型的列索引
- 使用.iloc將dummies各行的條目設(shè)為1
In [123]: gen = movies.genres[0]
In [124]: gen.split('|')
Out[124]: ['Animation', "Children's", 'Comedy']
In [125]: dummies.columns.get_indexer(gen.split('|'))
Out[125]: array([0, 1, 2])
In [126]: for i, gen in enumerate(movies.genres):
.....: indices = dummies.columns.get_indexer(gen.split('|'))
.....: dummies.iloc[i, indices] = 1
.....:
- 與movies合并起來
In [127]: movies_windic = movies.join(dummies.add_prefix('Genre_'))
In [128]: movies_windic.iloc[0]
Out[128]:
movie_id 1
title Toy Story (1995)
genres Animation|Children's|Comedy
Genre_Animation 1
Genre_Children's 1
Genre_Comedy 1
Genre_Adventure 0
Genre_Fantasy 0
Genre_Romance 0
Genre_Drama 0
...
Genre_Crime 0
Genre_Thriller 0
Genre_Horror 0
Genre_Sci-Fi 0
Genre_Documentary 0
Genre_War 0
Genre_Musical 0
Genre_Mystery 0
Genre_Film-Noir 0
Genre_Western 0
Name: 0, Length: 21, dtype: object
對于很大的數(shù)據(jù),用這種方式構(gòu)建多成員指標(biāo)變量就會非常慢。最好使用更低級的函數(shù),將其寫入NumPy數(shù)組,然后結(jié)果包裝在DataFrame中。
一個對統(tǒng)計應(yīng)用有用的秘訣是:結(jié)合get_dummies和cut之類的離散化函數(shù)
In [130]: values = np.random.rand(10)
In [131]: values
Out[131]:
array([ 0.9296, 0.3164, 0.1839, 0.2046, 0.5677, 0.5955, 0.9645,
0.6532, 0.7489, 0.6536])
In [132]: bins = [0, 0.2, 0.4, 0.6, 0.8, 1]
In [133]: pd.get_dummies(pd.cut(values, bins))
Out[133]:
(0.0, 0.2] (0.2, 0.4] (0.4, 0.6] (0.6, 0.8] (0.8, 1.0]
0 0 0 0 0 1
1 0 1 0 0 0
2 1 0 0 0 0
3 0 1 0 0 0
4 0 0 1 0 0
5 0 0 1 0 0
6 0 0 0 0 1
7 0 0 0 1 0
8 0 0 0 1 0
9 0 0 0 1 0
7.3 字符串操作
大部分文本運(yùn)算都直接做成了字符串對象的內(nèi)置方法。對于更為復(fù)雜的模式匹配和文本操作,則需要正則表達(dá)式。pandas能夠?qū)φM數(shù)據(jù)應(yīng)用字符串表達(dá)式和正則表達(dá)式,而且能處理缺失數(shù)據(jù)
字符串對象方法
- split常常與strip一起使用,以去除空白符(包括換行符)
- 利用加法,可以將這些子字符串連接
- 向字符串"::"的join方法傳入一個列表或元組
In [134]: val = 'a,b, guido'
In [136]: pieces = [x.strip() for x in val.split(',')]
In [137]: pieces
Out[137]: ['a', 'b', 'guido']
In [138]: first, second, third = pieces
In [139]: first + '::' + second + '::' + third
Out[139]: 'a::b::guido'
In [140]: '::'.join(pieces)
Out[140]: 'a::b::guido'
- 利用Python的in關(guān)鍵字檢測字串,還可以使用index和find
- 如果找不到字符串,index將會引發(fā)一個異常,find返回-1
In [141]: 'guido' in val
Out[141]: True
In [142]: val.index(',')
Out[142]: 1
In [143]: val.find(':')
Out[143]: -1
In [144]: val.index(':')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-144-280f8b2856ce> in <module>()
----> 1 val.index(':')
ValueError: substring not found
- count可以返回指定子串的出現(xiàn)次數(shù)
In [145]: val.count(',')
Out[145]: 2
replace用于將指定模式替換為另一個模式。通過傳入空字符串,它也常常用于刪除模式:
In [146]: val.replace(',', '::')
Out[146]: 'a::b:: guido'
In [147]: val.replace(',', '')
Out[147]: 'ab guido'


正則表達(dá)式
正則表達(dá)式是靈活的在文本中搜索或匹配字符串模式的方式。正則表達(dá)式,常稱作regex,是根據(jù)正則表達(dá)式語言編寫的字符串。Python內(nèi)置的re模塊負(fù)責(zé)對字符串應(yīng)用正則表達(dá)式
re模塊的函數(shù)可以分為三個大類:模式匹配、替換以及拆分。
要拆分一個字符串,分隔符為數(shù)量不定的一組空白符(制表符、空格、換行符等)。描述一個或多個空白符的regex是\s+
In [148]: import re
In [149]: text = "foo bar\t baz \tqux"
In [150]: re.split('\s+', text)
Out[150]: ['foo', 'bar', 'baz', 'qux']
- 對許多字符串應(yīng)用同一條正則表達(dá)式,最好用re.compile編譯regex創(chuàng)建regex對象
- 只希望得到匹配regex的所有模式,可以使用findall方法
In [151]: regex = re.compile('\s+')
In [152]: regex.split(text)
Out[152]: ['foo', 'bar', 'baz', 'qux']
In [153]: regex.findall(text)
Out[153]: [' ', '\t ', ' \t']
使用原始字符串字面量如r'C:\x'(也可以編寫其等價式'C:\x'),避免正則表達(dá)式中不需要的轉(zhuǎn)義(\)
- findall返回的是字符串中所有的匹配項(xiàng),
有一段文本以及一條能夠識別大部分電子郵件地址的正則表達(dá)式
text = """Dave dave@google.com
Steve steve@gmail.com
Rob rob@gmail.com
Ryan ryan@yahoo.com
"""
pattern = r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'
# re.IGNORECASE makes the regex case-insensitive
regex = re.compile(pattern, flags=re.IGNORECASE)
- 對text使用findall將得到一組電子郵件地址
In [155]: regex.findall(text)
Out[155]:
['dave@google.com',
'steve@gmail.com',
'rob@gmail.com',
'ryan@yahoo.com']
- search返回的是文本中第一個電子郵件地址(以特殊的匹配項(xiàng)對象形式返回),匹配項(xiàng)對象只能告訴我們模式在原字符串中的起始和結(jié)束位置
In [156]: m = regex.search(text)
In [157]: m
Out[157]: <_sre.SRE_Match object; span=(5, 20), match='dave@google.com'>
In [158]: text[m.start():m.end()]
Out[158]: 'dave@google.com'
- regex.match則將返回None,只匹配出現(xiàn)在字符串開頭的模式
In [159]: print(regex.match(text))
None
- sub方法將匹配到的模式替換為指定字符串,并返回所得到的新字符串
In [160]: print(regex.sub('REDACTED', text))
Dave REDACTED
Steve REDACTED
Rob REDACTED
Ryan REDACTED
- 將各個地址分成3個部分:用戶名、域名以及域后綴,只需將待分段的模式的各部分用圓括號包起來
- 通過groups方法返回一個由模式各段組成的元組
In [161]: pattern = r'([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})'
In [162]: regex = re.compile(pattern, flags=re.IGNORECASE)
In [163]: m = regex.match('wesm@bright.net')
In [164]: m.groups()
Out[164]: ('wesm', 'bright', 'net')
- 對于帶有分組功能的模式,findall會返回一個元組列表
In [165]: regex.findall(text)
Out[165]:
[('dave', 'google', 'com'),
('steve', 'gmail', 'com'),
('rob', 'gmail', 'com'),
('ryan', 'yahoo', 'com')]
- sub還能通過諸如\1、\2之類的特殊符號訪問各匹配項(xiàng)中的分組。符號\1對應(yīng)第一個匹配的組,\2對應(yīng)第二個匹配的組
In [166]: print(regex.sub(r'Username: \1, Domain: \2, Suffix: \3', text))
Dave Username: dave, Domain: google, Suffix: com
Steve Username: steve, Domain: gmail, Suffix: com
Rob Username: rob, Domain: gmail, Suffix: com
Ryan Username: ryan, Domain: yahoo, Suffix: com

pandas的矢量化字符串函數(shù)
含有字符串的列有時還含有缺失數(shù)據(jù)
In [169]: data
Out[169]:
Dave dave@google.com
Rob rob@gmail.com
Steve steve@gmail.com
Wes NaN
dtype: object
In [170]: data.isnull()
Out[170]:
Dave False
Rob False
Steve False
Wes True
dtype: bool
- 通過data.map,所有字符串和正則表達(dá)式方法都能被應(yīng)用于(傳入lambda表達(dá)式或其他函數(shù))各個值,但是如果存在NA(null)就會報錯。
- Series有能夠跳過NA值的面向數(shù)組方法,進(jìn)行字符串操作
- 通過Series的str屬性即可訪問這些方法
- 通過str.contains檢查各個電子郵件地址是否含有"gmail"
In [171]: data.str.contains('gmail')
Out[171]:
Dave False
Rob True
Steve True
Wes NaN
dtype: object
使用正則表達(dá)式,還可以加上任意re選項(xiàng)(如IGNORECASE)
In [172]: pattern
Out[172]: '([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\\.([A-Z]{2,4})'
In [173]: data.str.findall(pattern, flags=re.IGNORECASE)
Out[173]:
Dave [(dave, google, com)]
Rob [(rob, gmail, com)]
Steve [(steve, gmail, com)]
Wes NaN
dtype: object
實(shí)現(xiàn)矢量化的元素獲取操作:
- 使用str.get
- 在str屬性上使用索引
In [174]: matches = data.str.match(pattern, flags=re.IGNORECASE)
In [175]: matches
Out[175]:
Dave True
Rob True
Steve True
Wes NaN
dtype: object
- 要訪問嵌入列表中的元素,可以傳遞索引到這兩個函數(shù)中
In [176]: matches.str.get(1)
Out[176]:
Dave NaN
Rob NaN
Steve NaN
Wes NaN
dtype: float64
In [177]: matches.str[0]
Out[177]:
Dave NaN
Rob NaN
Steve NaN
Wes NaN
dtype: float64
可以利用這種方法對字符串進(jìn)行截取
In [178]: data.str[:5]
Out[178]:
Dave dave@
Rob rob@g
Steve steve
Wes NaN
dtype: object
