說說Python中的pandas模塊(2)

上次說到了pandas中常用的一些選擇以及切片的方法,總結(jié)一下拴泌,主要有以下幾種:

data['A’]

data[['A','B’]]

data.iloc[:,1] #截取第二列數(shù)據(jù),iloc只能用數(shù)字截取, Select row by integer location

data.loc[2] #截取index label為2的第二行數(shù)據(jù),loc只能用label來截取器联,Select row by label

data.loc[:,'A':'B’] #截取截取從header為’A’到’B’的列

data.ix[:, ‘A’:'B’] #截取從header為’A’到’B’的列
data.ix[:,0:2] #截取前兩列數(shù)據(jù)

有一點(diǎn)要注意:
In pandas version 0.20.0 and above, ix is deprecated and the use of loc and iloc is encouraged instead.

在pandas最新的documentation里,loc和iloc是比較推薦使用的婿崭,在stack overflow上有個(gè)問題專門問了這三種截取方法的區(qū)別拨拓,這里引用一下一遍我們深入了解他們的區(qū)別:

loc works on labels in the index. 
iloc works on the positions in the index (so it only takes integers).
ix usually tries to behave like loc but falls back to behaving like iloc if the label is not in the index.

舉個(gè)栗子,如果一個(gè)data frame, 它的index label是mixed type氓栈,既包含數(shù)字類型渣磷,又包含文本類型,那么ix既可用位置數(shù)字去截取授瘦,也可以用label去截取, 但是一定要記住醋界,ix是優(yōu)先label的竟宋,如果label不存在,就會(huì)用位置數(shù)字去截取 (僅僅在mixed type下適用形纺,一旦我們的label是固定類型丘侠,那么ix和loc的作用就完全一樣了)

接下來我想說一說數(shù)據(jù)過濾的問題, 這個(gè)問題也是我在數(shù)據(jù)預(yù)處理的時(shí)候經(jīng)常遇到的問題,我們先來創(chuàng)建一個(gè)數(shù)據(jù)表, 包含一些城市的信息

import pandas as pd

data = pd.read_excel('rhythm.xlsx')
print data

Out[23]:
   A  B  C  D      city  house_price  \
0  1  2  3  4   Beijing        70000   
1  2  2  3  4  Shanghai       120000   
2  3  2  3  4       NaN         5000   
3  4  2  3  4  New York       140000   
4  5  2  3  4  Brasilia        50000   
5  6  2  3  4   Atlanta        20000   
6  7  2  3  4     Tokyo       130000   
7  8  2  3  4     #NAME        30000   

                                         information  
0                                     page not found  
1  Shanghai is a Chinese city located on the east...  
2  Kunming is also called the Spring city due to ...  
3  New York is a state in the northeastern United...  
4  Brasília (Portuguese pronunciation: [b?a?zilj?...  
5                                      404 not found  
6  Tokyo (Japanese: [to?kjo?] ( listen), English ...  
7  Mumbai (/m?m?ba?/; also known as Bombay, the o...  

我們可以看到逐样,這個(gè)dataset有很多問題蜗字,比如city列有NaN數(shù)據(jù)缺失的問題,information列有’page not found’的錯(cuò)誤信息脂新,我們要怎么剔除這些信息呢挪捕?

第一問:如果我想把city列含有NaN的行去掉,要怎么做呢争便?
drop_nan = data.dropna(subset=['city'])
print drop_nan

output:
  A  B  C  D      city  house price  \
0  1  2  3  4   Beijing        70000   
1  2  2  3  4  Shanghai       120000   
3  4  2  3  4  New York       140000   
4  5  2  3  4  Brasilia        50000   
5  6  2  3  4   Atlanta        20000   
6  7  2  3  4     Tokyo       130000   

                                         information  
0                                     page not found  
1  Shanghai is a Chinese city located on the east...  
3  New York is a state in the northeastern United...  
4  Brasília (Portuguese pronunciation: [b?a?zilj?...  
5                                      404 not found  
6  Tokyo (Japanese: [to?kjo?] ( listen), English ...  

可以看到级零,我們city缺失的那一行已經(jīng)完全消失了,dropna就是專門用于過濾空值的函數(shù)滞乙,一般來說它有兩種形式:

data.dropna(how='any') #to drop if any value in the row has a nan 只要任何一列包含有na值妄讯,就會(huì)完全刪除那一行

data.dropna(how='all') #to drop if all values in the row are nan 如果所有列的值都是na,才刪除那一行

在這里酷宵,需要注意行和列的區(qū)別

第二問:我想把東京和亞特蘭大那兩行刪掉
drop_value = data[data.city.str.contains('Tokyo', 'Atlanta') == False]

#or

drop_value = data[~data.city.str.contains('Tokyo', 'Atlanta',na=False)]

output:
A  B  C  D      city  house price  \
0  1  2  3  4   Beijing        70000   
1  2  2  3  4  Shanghai       120000   
2  3  2  3  4       NaN         5000   
3  4  2  3  4  New York       140000   
4  5  2  3  4  Brasilia        50000   

                                         information  
0                                     page not found  
1  Shanghai is a Chinese city located on the east...  
2  Kunming is also called the Spring city due to ...  
3  New York is a state in the northeastern United...  
4  Brasília (Portuguese pronunciation: [b?a?zilj?...  
第三問,我想把house price 大于等于70000小于等于14000的行提取出來:

在做這一步之前躬窜,有個(gè)很重要的問題需要我們先解決了浇垦,仔細(xì)觀察我們這個(gè)數(shù)據(jù)集,就會(huì)發(fā)現(xiàn)“house price”這個(gè)header是包含有空格的荣挨,這對(duì)我們之后的數(shù)據(jù)處理會(huì)造成很大麻煩男韧,所以我們需要先把這個(gè)空格替換為”_"

data.columns = [c.replace(' ', '_') for c in data.columns]

print data.columns.values

output:
[u'A' u'B' u'C' u'D' u'city' u'house_price' u'information']

接下來就可以進(jìn)行數(shù)字的范圍截取了:

select_range = data[(data.house_price >= 70000) & (data.house_price <= 140000)]

output:
   A  B  C  D      city  house_price  \
0  1  2  3  4   Beijing        70000   
1  2  2  3  4  Shanghai       120000   
3  4  2  3  4  New York       140000   
6  7  2  3  4     Tokyo       130000   

                                         information  
0                                     page not found  
1  Shanghai is a Chinese city located on the east...  
3  New York is a state in the northeastern United...  
6  Tokyo (Japanese: [to?kjo?] ( listen), English ...  
第四問:我想把information那一列中,包含“page not found”, “404 not found”這些文本的行刪除默垄,并且此虑,如果city一列中,開頭的第一個(gè)文本是符號(hào)”#",那么也將這一行刪除

ignore_list = ['404 not found','page not found']

remove_start_with = data[~data['city'].str.startswith('#', na=False)
                       & ~data['information'].str.contains('|'.join(ignore_list), na=True)]

print remove_start_with

A  B  C  D      city  house_price  \
1  2  2  3  4  Shanghai       120000   
2  3  2  3  4       NaN         5000   
3  4  2  3  4  New York       140000   
4  5  2  3  4  Brasilia        50000   
6  7  2  3  4     Tokyo       130000   

                                         information  
1  Shanghai is a Chinese city located on the east...  
2  Kunming is also called the Spring city due to ...  
3  New York is a state in the northeastern United...  
4  Brasília (Portuguese pronunciation: [b?a?zilj?...  
6  Tokyo (Japanese: [to?kjo?] ( listen), English ...
第五問口锭,我想把截取information文本長(zhǎng)度大于30個(gè)詞的行

len_filter = data[data.information.str.len() >= 30]

print len_filter

從上面的各種例子來看朦前,我們就會(huì)發(fā)現(xiàn),pandas在截取數(shù)據(jù)鹃操,過濾數(shù)據(jù)的時(shí)候功能強(qiáng)大韭寸,且寫出的代碼可讀性極高。我會(huì)繼續(xù)復(fù)習(xí)pandas相關(guān)的知識(shí)荆隘,在下一篇文章中說談?wù)勅绾斡胮andas內(nèi)聯(lián)結(jié)兩個(gè)數(shù)據(jù)集恩伺。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市椰拒,隨后出現(xiàn)的幾起案子晶渠,更是在濱河造成了極大的恐慌凰荚,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,858評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件褒脯,死亡現(xiàn)場(chǎng)離奇詭異便瑟,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)憨颠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門胳徽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人爽彤,你說我怎么就攤上這事养盗。” “怎么了适篙?”我有些...
    開封第一講書人閱讀 165,282評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵往核,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我嚷节,道長(zhǎng)聂儒,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,842評(píng)論 1 295
  • 正文 為了忘掉前任硫痰,我火速辦了婚禮衩婚,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘效斑。我一直安慰自己非春,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評(píng)論 6 392
  • 文/花漫 我一把揭開白布缓屠。 她就那樣靜靜地躺著奇昙,像睡著了一般。 火紅的嫁衣襯著肌膚如雪敌完。 梳的紋絲不亂的頭發(fā)上储耐,一...
    開封第一講書人閱讀 51,679評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音滨溉,去河邊找鬼什湘。 笑死,一個(gè)胖子當(dāng)著我的面吹牛业踏,可吹牛的內(nèi)容都是我干的禽炬。 我是一名探鬼主播,決...
    沈念sama閱讀 40,406評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼勤家,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼腹尖!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,311評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤热幔,失蹤者是張志新(化名)和其女友劉穎乐设,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體绎巨,經(jīng)...
    沈念sama閱讀 45,767評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡近尚,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了场勤。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片戈锻。...
    茶點(diǎn)故事閱讀 40,090評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖和媳,靈堂內(nèi)的尸體忽然破棺而出格遭,到底是詐尸還是另有隱情,我是刑警寧澤留瞳,帶...
    沈念sama閱讀 35,785評(píng)論 5 346
  • 正文 年R本政府宣布拒迅,位于F島的核電站,受9級(jí)特大地震影響她倘,放射性物質(zhì)發(fā)生泄漏璧微。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評(píng)論 3 331
  • 文/蒙蒙 一硬梁、第九天 我趴在偏房一處隱蔽的房頂上張望前硫。 院中可真熱鬧,春花似錦荧止、人聲如沸开瞭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至个扰,卻和暖如春瓷炮,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背递宅。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評(píng)論 1 271
  • 我被黑心中介騙來泰國(guó)打工娘香, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人办龄。 一個(gè)月前我還...
    沈念sama閱讀 48,298評(píng)論 3 372
  • 正文 我出身青樓烘绽,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親俐填。 傳聞我的和親對(duì)象是個(gè)殘疾皇子安接,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容