#2.1.5 Working With Missing Data.md

1.NaN(空值)與None(缺失值)

Missing data can take a few different forms:

  • In Python, the None
    keyword and type indicates no value.
  • The Pandas library uses NaN
    , which stands for "not a number", to indicate a missing value.

In general terms, both NaN and None can be called null values.

2.判斷缺失值/空字符:pandas.isnull(XXX)

If we want to see which values are NaN, we can use the pandas.isnull() function which takes a pandas series and returns a series of True and False
values, the same way that NumPy did when we compared arrays.

input
age = titanic_survival["age"]
print(age.loc[10:20])
age_is_null = pandas.isnull(age)    # 如果是NaN或者None,返回True办陷;否則蓬网,返回False
age_null_true = age[age_is_null]    # 
age_null_count = len(age_null_true)
print(age_null_count)
output
10    47.0 
11    18.0 
12    24.0 
13    26.0 
14    80.0 
15     NaN 
16    24.0 
17    50.0 
18    32.0 
19    36.0 
20    37.0 
Name: age, dtype: float64 
264

3.有null值時(shí)做加減乘除法


#計(jì)算有null值下的平均年齡

age_is_null = pd.isnull(titanic_survival["age"])

good_ages = titanic_survival['age'][age_is_null == False]

correct_mean_age1 = sum(good_ages) / len(good_ages)

#使用Series.mean()

correct_mean_age2 = titanic_survival["age"].mean()

4.用詞典統(tǒng)計(jì)不同等級(jí)船艙的票價(jià)問(wèn)題

input

passenger_classes = [1, 2, 3]  #泰坦尼克的船艙等級(jí)分為1爱只,2与纽,3

fares_by_class = {}   #創(chuàng)建一個(gè)空字典

for this_class in passenger_classes:
    pclass_rows = titanic_survival[titanic_survival['pclass'] == this_class]  # X等艙的所有數(shù)據(jù)
    mean_fares = pclass_rows['fare'].mean()   # X等艙的船票均值
    fares_by_class[this_class] = mean_fares  # 構(gòu)建詞典用于統(tǒng)計(jì)
print(fares_by_class)
output
{1: 87.508991640866881, 2: 21.179196389891697, 3: 13.302888700564973}

5.使用Dataframe.pivot_table()

Pivot tables provide an easy way to subset by one column and then apply a calculation like a sum or a mean.

剛才第4點(diǎn)的問(wèn)題赦颇,可以用Dataframe.pivot_table()

  • The first parameter of the method, index
    tells the method which column to group by.

  • The second parameter values
    is the column that we want to apply the calculation to.

  • aggfunc
    specifies the calculation we want to perform. The default for the aggfunc
    parameter is actually the mean

input1

passenger_class_fares = titanic_survival.pivot_table(index="pclass", values="fare", aggfunc=numpy.mean)

print(passenger_class_fares)

output1

pclass 

1.0    87.508992 

2.0    21.179196 

3.0    13.302889 

Name: fare, dtype: float64

input2

passenger_age = titanic_survival.pivot_table(index="pclass", values="age",aggfunc=numpy.mean)

print(passenger_age)

output2
pclass 
1.0    39.159918 
2.0    29.506705 
3.0    24.816367 
Name: age, dtype: float64
input3
import numpy as np
port_stats = titanic_survival.pivot_table(index='embarked', values=["fare", "survived"], aggfunc=numpy.sum)
print(port_stats)

output3
                fare  survivedembarked                      C         16830.7922     150.0Q          1526.3085      44.0S         25033.3862     304.0

6.剔除缺失值:DataFrame.dropna()

The methodDataFrame.dropna()
will drop any rows that contain missing values.

drop_na_rows = titanic_survival.dropna(axis=0)  # 剔除所有含缺失值的行
drop_na_columns = titanic_survival.dropna(axis=1) # 剔除所有含缺失值的列
new_titanic_survival = titanic_survival.dropna(axis=0,subset=["age", "sex"])  # 剔除所有在‘a(chǎn)ge’和‘sex’中嗜桌,有缺失值的行

7.Dataframe.loc[4]與Dataframe.iloc[4]

input

# We have already sorted new_titanic_survival by age
first_five_rows_1 = new_titanic_survival.iloc[5]   # 定位到按順序第5的對(duì)象
first_five_rows_2 = new_titanic_survival.loc[5]   # 定位到索引值為5的對(duì)象
row_index_25_survived = new_titanic_survival.loc[25, 'survived']  # 定位到索引值為5,且列名為'survived'的對(duì)象
print(first_five_rows_1)
print('------------------------------------------')
print(first_five_rows_2)
output
pclass                          3survived                        0name         Connors, Mr. Patricksex                          maleage                          70.5sibsp                           0parch                           0ticket                     370369fare                         7.75cabin                         NaNembarked                        Qboat                          NaNbody                          171home.dest                     NaNName: 727, dtype: object------------------------------------------pclass                         1survived                       1name         Anderson, Mr. Harrysex                         maleage                           48sibsp                          0parch                          0ticket                     19952fare                       26.55cabin                        E12embarked                       Sboat                           3body                         NaNhome.dest           New York, NYName: 5, dtype: object

8.重新整理索引值:Dataframe.reset_index(drop=True)

input

titanic_reindexed = new_titanic_survival.reset_index(drop=True)
print(titanic_reindexed.iloc[0:5,0:3])
output
   pclass  survived                                               name0     1.0       1.0               Barkworth, Mr. Algernon Henry Wilson1     1.0       1.0  Cavendish, Mrs. Tyrell William (Julia Florence...2     3.0       0.0                                Svensson, Mr. Johan3     1.0       0.0                          Goldschmidt, Mr. George B4     1.0       0.0                            Artagaveytia, Mr. Ramon

9.Apply Functions Over a DataFrame

DataFrame.apply() will iterate through each column in a DataFrame, and perform on each function. When we create our function, we give it one parameter, apply() method passes each column to the parameter as a pandas series.
DataFrame可以調(diào)用apply函數(shù)對(duì)每一列(行)應(yīng)用一個(gè)函數(shù)

input
def not_null_count(column):
    columns_null = pandas.isnull(column)  #
    null = column[column_null]
    return len(null)
column_null_count = titanic_survival.apply(not_null_count)
print(column_null_count)
output
pclass          1survived        1name            1sex             1age           264sibsp           1parch           1ticket          1fare            2cabin        1015embarked        3boat          824body         1189home.dest     565dtype: int64

10.Applying a Function to a Row

input

def age_label(row):
    age = row['age']
    if pandas.isnull(age):
        return 'unknown'
    elif age < 18:
        return 'minor'
    else:
        return 'adult'
age_labels = titanic_survival.apply(age_label, axis=1)  # use axis=1
 so that the apply()
 method applies your function over the rows 
print(age_labels[0:5])
output
0    adult1    minor2    minor3    adult4    adultdtype: object

11.Calculating Survival Percentage by Age Group

Now that we have age labels for everyone, let's make a pivot table to find the probability of survival for each age group.
We have added an "age_labels"
column to the dataframe containing the age_labels
variable from the previous step.

input
age_group_survival = titanic_survival.pivot_table(index="age_labels", values="survived")
print(age_group_survival)
output
age_labelsadult      0.387892minor      0.525974unknown    0.277567Name: survived, dtype: float64
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末好港,一起剝皮案震驚了整個(gè)濱河市愉镰,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌钧汹,老刑警劉巖岛杀,帶你破解...
    沈念sama閱讀 222,681評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異崭孤,居然都是意外死亡类嗤,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)辨宠,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)遗锣,“玉大人,你說(shuō)我怎么就攤上這事嗤形【ィ” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,421評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵赋兵,是天一觀的道長(zhǎng)笔咽。 經(jīng)常有香客問(wèn)我,道長(zhǎng)霹期,這世上最難降的妖魔是什么叶组? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 60,114評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮历造,結(jié)果婚禮上甩十,老公的妹妹穿的比我還像新娘。我一直安慰自己吭产,他們只是感情好侣监,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,116評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著臣淤,像睡著了一般橄霉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上邑蒋,一...
    開(kāi)封第一講書(shū)人閱讀 52,713評(píng)論 1 312
  • 那天姓蜂,我揣著相機(jī)與錄音,去河邊找鬼寺董。 笑死覆糟,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的遮咖。 我是一名探鬼主播滩字,決...
    沈念sama閱讀 41,170評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了麦箍?” 一聲冷哼從身側(cè)響起漓藕,我...
    開(kāi)封第一講書(shū)人閱讀 40,116評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎挟裂,沒(méi)想到半個(gè)月后享钞,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,651評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡诀蓉,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,714評(píng)論 3 342
  • 正文 我和宋清朗相戀三年栗竖,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片渠啤。...
    茶點(diǎn)故事閱讀 40,865評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡狐肢,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出沥曹,到底是詐尸還是另有隱情份名,我是刑警寧澤,帶...
    沈念sama閱讀 36,527評(píng)論 5 351
  • 正文 年R本政府宣布妓美,位于F島的核電站僵腺,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏壶栋。R本人自食惡果不足惜辰如,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,211評(píng)論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望委刘。 院中可真熱鬧丧没,春花似錦、人聲如沸锡移。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,699評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)淆珊。三九已至,卻和暖如春奸汇,著一層夾襖步出監(jiān)牢的瞬間施符,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,814評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工擂找, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留戳吝,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,299評(píng)論 3 379
  • 正文 我出身青樓贯涎,卻偏偏與公主長(zhǎng)得像听哭,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,870評(píng)論 2 361

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

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,585評(píng)論 0 23
  • 媽媽 我昨晚做夢(mèng)了 夢(mèng)到兩個(gè)你 兩個(gè)你長(zhǎng)得一樣 脾氣不一樣 一個(gè)脾氣是好的 一個(gè)脾氣是壞的粗糙的很兇的 我還夢(mèng)到咱...
    每日愛(ài)圖閱讀 148評(píng)論 0 0
  • 在我們家發(fā)現(xiàn)了折疊的桌子陆盘、指揮棒普筹、臟衣收納袋。都是為了平時(shí)節(jié)省空間隘马,有需要時(shí)打開(kāi)就可以了太防。 在網(wǎng)上找到了幾樣我喜歡...
    小熊愛(ài)吃閱讀 191評(píng)論 0 0
  • 淌過(guò)上個(gè)世紀(jì)的海水,拖贅憊懶的皮囊酸员,松垮泛白蜒车,像胃里爬出來(lái)的一塊軟泡囊腫,你試圖抖擻精神幔嗦,釋放靈魂酿愧,振奮的皮屑在陽(yáng)...
    張二天閱讀 228評(píng)論 7 0
  • 我從小生活的地方,我見(jiàn)慣了的風(fēng)光崭添, 多少次夢(mèng)里花落寓娩,醒來(lái)確身在異鄉(xiāng)。
    每個(gè)人的孟母堂閱讀 107評(píng)論 0 1