1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        Pandas清洗數(shù)據(jù)的4個(gè)實(shí)用小技巧

        共 3048字,需瀏覽 7分鐘

         ·

        2021-03-24 13:39


        大家好,歡迎來到 Crossin的編程教室 !
        pandas 是做數(shù)據(jù)分析時(shí)的必備庫。在數(shù)據(jù)分析之前,我們往往需要對(duì)數(shù)據(jù)的大小、內(nèi)容、格式做一定處理,去掉無效值和缺失值,保持結(jié)構(gòu)統(tǒng)一,使其便于之后的分析。這一過程被稱作“數(shù)據(jù)清洗”。
        今天我們就來分享幾個(gè)Pandas在做數(shù)據(jù)清洗時(shí)的小技巧,內(nèi)容不長(zhǎng),但很實(shí)用。

        1. 讀取時(shí)抽樣 1%

        對(duì)于動(dòng)輒就幾十或幾百個(gè) G 的數(shù)據(jù),在讀取這么大數(shù)據(jù)時(shí),有沒有辦法隨機(jī)選取一小部分?jǐn)?shù)據(jù),然后讀入內(nèi)存,快速了解數(shù)據(jù)和開展 EDA ?

        使用 Pandas 的 skiprows 和 概率知識(shí),就能做到。

        下面解釋具體怎么做。

        如下所示,讀取某 100 G 大小的 big_data.csv 數(shù)據(jù)

        1. 使用 skiprows 參數(shù),

        2. x > 0 確保首行讀入,

        3. np.random.rand() > 0.01 表示 99% 的數(shù)據(jù)都會(huì)被隨機(jī)過濾掉

        言外之意,只有全部數(shù)據(jù)的 1% 才有機(jī)會(huì)選入內(nèi)存中。

        import pandas as pd
        import numpy as np

        df = pd.read_csv("big_data.csv",
        skiprows = lambda x: x>0 and
        np.random.rand() > 0.01)

        print("The shape of the df is {}.
        It has been reduced 100 times!"
        .format(df.shape))

        使用這種方法,讀取的數(shù)據(jù)量迅速縮減到原來的 1% ,對(duì)于迅速展開數(shù)據(jù)分析有一定的幫助。

        2. replace 做清洗

        清洗數(shù)據(jù)時(shí),少不了要對(duì)數(shù)據(jù)內(nèi)容進(jìn)行查找替換。

        這里有一個(gè)快速清洗數(shù)據(jù)的小技巧,在某列上使用 replace 方法和正則,快速完成值的清洗。

        源數(shù)據(jù):

        d = {"customer": ["A", "B", "C", "D"],
        "sales":[1100, "950.5RMB", "$400", " $1250.75"]}

        df = pd.DataFrame(d)
        df

        打印結(jié)果:


        customer sales
        0 A 1100
        1 B 950.5RMB
        2 C $400
        3 D $1250.75

        看到 sales 列的值,有整型,浮點(diǎn)型+RMB后變?yōu)樽址?,還有美元+整型,美元+浮點(diǎn)型。

        我們的目標(biāo):清洗掉 RMB,$ 符號(hào),轉(zhuǎn)化這一列為浮點(diǎn)型。

        一行代碼搞定:(點(diǎn)擊代碼區(qū)域,向右滑動(dòng),查看完整代碼)

        df["sales"] = df["sales"].replace("[$,RMB]", "", regex = True).astype("float")

        使用正則替換,將要替換的字符放到列表中 [$,RMB],替換為空字符,即 "";

        最后使用 astype 轉(zhuǎn)為 float

        打印結(jié)果:


        customer sales
        0 A 1100.00
        1 B 950.50
        2 C 400.00
        3 D 1250.75

        Done ~

        如果不放心,再檢查下值的類型:

        df["sales"].apply(type)

        打印結(jié)果:

        0    <class 'float'>
        1 <class 'float'>
        2 <class 'float'>
        3 <class 'float'>

        3. 寬 DF 變長(zhǎng)

        為什么需要寬 DF 變長(zhǎng) ?

        構(gòu)造一個(gè) DataFrame:

        d = {\
        "district_code": [12345, 56789, 101112, 131415],
        "apple": [5.2, 2.4, 4.2, 3.6],
        "banana": [3.5, 1.9, 4.0, 2.3],
        "orange": [8.0, 7.5, 6.4, 3.9]
        }

        df = pd.DataFrame(d)
        df

        打印結(jié)果:


        district_code apple banana orange
        0 12345 5.2 3.5 8.0
        1 56789 2.4 1.9 7.5
        2 101112 4.2 4.0 6.4
        3 131415 3.6 2.3 3.9

        5.2 表示 12345 區(qū)域的 apple 價(jià)格,并且 apple, banana, orange,這三列都是一種水果,那么如何把這三列合并為一列?

        使用 pd.melt

        具體參數(shù)取值,大家根據(jù)此例去推敲:

        df = df.melt(\
        id_vars = "district_code",
        var_name = "fruit_name",
        value_name = "price")
        df

        打印結(jié)果:


        district_code fruit_name price
        0 12345 apple 5.2
        1 56789 apple 2.4
        2 101112 apple 4.2
        3 131415 apple 3.6
        4 12345 banana 3.5
        5 56789 banana 1.9
        6 101112 banana 4.0
        7 131415 banana 2.3
        8 12345 orange 8.0
        9 56789 orange 7.5
        10 101112 orange 6.4
        11 131415 orange 3.9

        以上就是長(zhǎng) DataFrame,對(duì)應(yīng)的原 DataFrame 是寬 DF.

        看明白了嗎?

        4. 轉(zhuǎn) datetime

        告訴 year(年份)和 dayofyear(一年中的第幾天,怎么轉(zhuǎn) datetime?

        原 DataFrame

        d = {\
        "year": [2019, 2019, 2020],
        "day_of_year": [350, 365, 1]
        }
        df = pd.DataFrame(d)
        df

        打印結(jié)果:

          year	day_of_year
        0 2019 350
        1 2019 365
        2 2020 1

        轉(zhuǎn) datetime 的 trick。

        Step 1: 創(chuàng)建整數(shù)

        df["int_number"] = df["year"]*1000 + df["day_of_year"]
        df

        打印結(jié)果:

        year	day_of_year	int_number
        0 2019 350 2019350
        1 2019 365 2019365
        2 2020 1 2020001

        Step 2: to_datetime

        df["date"] = pd.to_datetime(df["int_number"], format = "%Y%j")
        df

        注意 "%Y%j" 中轉(zhuǎn)化格式 j

        打印結(jié)果:

        	year	day_of_year	int_number	date
        0 2019 350 2019350 2019-12-16
        1 2019 365 2019365 2019-12-31
        2 2020 1 2020001 2020-01-01

        以上就是 Pandas 做數(shù)據(jù)清洗的4個(gè) 小技巧。

        如果文章對(duì)你有幫助,歡迎轉(zhuǎn)發(fā)/點(diǎn)贊/收藏~

        作者:zglg

        來源:Python與算法社區(qū)


        _往期文章推薦_

        【一圖流】Pandas官方速查表




        如需了解付費(fèi)精品課程教學(xué)答疑服務(wù)
        請(qǐng)?jiān)?strong style="max-width: 100%;overflow-wrap: break-word !important;box-sizing: border-box !important;">Crossin的編程教室內(nèi)回復(fù): 666

        瀏覽 56
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            网红被c 到爽的在线观看 | 91丨九色丨熟女泻火 | 一级黄色视频片 | freehdxxxxjapanmovie | 亚洲图片激情小说 | 中国青年男女人人爱肏逼 | 老女人色一区二区三区视频 | av中文无码 | 日韩黄色一级 | 操操操操av |