乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      機器學習之Pandas教程(上)

       愛睡覺的貓 2021-02-03

      1. 教程簡介

             本教程分為上、下兩節(jié),主要針對機器學習數(shù)據(jù)處理做的簡單教程。本教程主要不是講解pandas函數(shù)的使用,而是實驗性的操作學習方式,對于使用本教程的學者,可以根據(jù)課程一步一步去實驗,對于不懂的函數(shù)以及實現(xiàn)方式可以在官網(wǎng)進行查詢。注意,重點還是動手自己操作。

      2. Pandas簡介

               pandas 是基于NumPy 的一種工具,該工具是為了解決數(shù)據(jù)分析任務(wù)而創(chuàng)建的。Pandas 納入了大量庫和一些標準的數(shù)據(jù)模型,提供了高效地操作大型數(shù)據(jù)集所需的工具。pandas提供了大量能使我們快速便捷地處理數(shù)據(jù)的函數(shù)和方法。pandas有三種數(shù)據(jù)結(jié)構(gòu)形式,分別是Series,DataFrame和索引對象。本教程上節(jié)也主要是講解著幾種結(jié)構(gòu)形式,下節(jié)講解pandas在特征工程中常用的操作。

      3. Series結(jié)構(gòu)

      3.1 構(gòu)造和初始化Series

      import pandas as pdimport numpy as np

      3.1.1 通過list來構(gòu)建

      # Series是一個一維的數(shù)據(jù)結(jié)構(gòu),下面是一些初始化Series的方法s = pd.Series([5, 9, "shanghai","shenzhen",7,5.2])s

      輸出:

      # 切片讀取s[1:3]

      輸出:

      # pandas會默認用0到n-1來作為Series的index,但是我們也可以自己指定index。index我們可以把它理解為dict里面的key。s = pd.Series([5, 9, "shanghai","shenzhen",5.2],index=["A", "B", "C", "D", "E"])s

      輸出:

      # 通過制定的key獲取元素s["C"]

      輸出:  'shanghai'

      3.1.2 通過dictionary來構(gòu)建

      cities = {"Shanghai": 90000, "Foshan": 4500, "Dongguan": 5500, "Beijing": 6600, "Nanjing": 8000, "Lanzhou": None}apts = pd.Series(cities, name="price")apts

      輸出:


      3.1.2 通過numpy ndarray來構(gòu)建

      s = pd.Series(np.random.randn(6), index=list("abcdef"))s

      輸出:

      3.2 數(shù)據(jù)的選擇

              對于Series我們可以向list一樣進行元素的獲取。

      3.2.1 通過list方式

      cities = {"Shanghai": 90000, "Foshan": 4500, "Dongguan": 5500, "Beijing": 6600, "Nanjing": 8000, "Lanzhou": None}apts = pd.Series(cities, name="price")# 獲取元素 list方式apts[[4,3,2]]

      輸出:

      3.2.2 通過切片方式

      # 切片方式apts[3:]

      輸出:


      # 切片方式 :-2表示從0到末尾第二個apts[:-2]

      輸出:


      # 讀取到倒數(shù)第一個apts[:-1]

      輸出:


      # 從第一個到最后一個apts[1:]

      輸出:


      3.2.2 通過key獲取

      # 通過key獲取,前面定義的index就是用來選擇數(shù)據(jù)的apts["Shanghai"]

      輸出:90000.0

      # 通過key組成的list獲取元素,對于Series沒有的就返回空apts[["Shenzhen", "Nanjing", "Dongguan"]]

      輸出:

      3.2.3 判斷元素是否存在

      "Shanghai" in apts

      輸出:True

      "Chongqing" in apts

      輸出:False

      3.2.4 用get讀取元素

      # 用讀取元素,當Series中沒有這個元素時,可以返回我們制定的數(shù),這里定義為0apts.get("Shanghai", 0)

      輸出:90000.0

      # apts中沒有Shenzhenapts.get("Shenzhen", 0)
      輸出:0

      3.2.5 用過bool類型獲取元素

      #獲取小于7000的元素apts[apts < 7000]

      輸出:

      # 返回大于平均值的數(shù)apts[apts > apts.median()]

      輸出:


      # 具體的過程less_than_7000 = apts < 50000less_than_7000

      輸出:

      apts[less_than_7000]

      輸出:

      3.3 Series元素賦值

          對于Series賦值非常簡單,對于以上我們已經(jīng)拿到了Series,那我們可以直接對其賦值就可以。

      apts["Shanghai"] = 68000apts

      輸出:

      # 小于50000的都賦值給60000apts[apts < 50000] = 60000apts

      輸出:

      3.4 Series數(shù)學運算

      # 每個元素都乘上2apts * 2

      輸出:

      # 每個元素都除于2apts / 2

      輸出:

      # 每個元素都加上10000,但是對于值為NAN的元素你做運算apts + 10000

      輸出:

      # 平方運算apts ** 2

      輸出:

      # 開根號np.square(apts)

      輸出:

      3.5 缺損值處理

      # 判斷哪個值不是NaNapts.notnull()

      輸出:

      # 判斷是否有NaNapts.isnull()

      輸出:

      # 對缺損值進行填充apts[apts.isnull()] = apts.mean()apts

      輸出:

      4. Dataframe結(jié)構(gòu)

              Dataframe就像是一張表格,而Series表示的是一個以為數(shù)組,Dataframe則是一個二維數(shù)組,可以類比成一張Excel表格,而是Dataframe的一行或者一列則是一個Series。對于Dataframe的行用index表示,列用columns表示。

      4.1 Dataframe的創(chuàng)建

      4.1.1 通過dictionary創(chuàng)建

              dataframe可以是有一個dictionary構(gòu)造來創(chuàng)建。

      data = {'city': ['Shanghai', 'Nanjing', 'Lanzhou', 'Shangsha', 'Guizhou', 'Xian'],'year': [2017,2018,2017,2018,2018,2017],'population': [2100, 600, 800, 700, 560, 900]}pd.DataFrame(data)

      輸出:

      # 可以指定columns的名字和順序pd.DataFrame(data, columns=["year", "city", "population"])

      輸出:

      # 創(chuàng)建時指定index和columnsframe = pd.DataFrame(data, columns=["year", "city", "population", "debt"],index=["one", "two", "three", "four", "five", "six"])frame

      輸出:


      4.1.2 通過Series創(chuàng)建

      cars = pd.Series({"Beijing": 300000, "Shanghai": 350000, "Shenzhen": 300000,                 "Tianjian": 200000, "Guangzhou": 250000, "Chongqing": 150000})cities = {"Shanghai": 90000, "Foshan": 4500, "Dongguan": 5500, "Beijing": 6600, "Nanjing": 8000, "Lanzhou": None}apts = pd.Series(cities, name="price")df = pd.DataFrame({"apts": apts, "cars": cars})df

      輸出:

      4.1.3 通過dicts的list來構(gòu)建Dataframe

      data = [{"Beijing": 1000, "Shanghai": 2500, "Nanjing": 9850}, {"Beijing": 5000, "Shanghai": 4600, "Nanjing": 7000}]pd.DataFrame(data)

      輸出:

      # 定義indexdata = [{"Beijing": 1000, "Shanghai": 2500, "Nanjing": 9850}, {"Beijing": 5000, "Shanghai": 4600, "Nanjing": 7000}]pd.DataFrame(data, index=["salary", "other"])

      輸出:

      4.2 獲取Dataframe的值 

      4.2.1 通過列名的方式

      # 通過列名frame["city"]
      輸出:

      # 也可以用這種方式,與上面的效果一樣frame.year

      輸出:

      # 判斷類型type(frame.year)
      輸出:pandas.core.series.Series

      4.2.2 通過loc函數(shù)

      # 通過自己定義的index獲取frame.loc["three"]

      輸出:

      # 通過行列名字或者frame.loc["three", "city"]

      輸出:Lanzhou

      4.2.2 通過iloc函數(shù)

              通過iloc方法可以拿到行和列,直接按照index的順序來取??梢援斪鰊umpy的ndarray的二維數(shù)組來操作。

      # 獲取前三行frame.iloc[0:3]

      輸出:


      # 切片操作frame.iloc[0:3, 1:3]

      輸出:

      4.3 Dataframe賦值

              對于以上獲取到Dataframe以后,要想對其賦值是很簡單的。

      frame.loc["one", "population"] = 5555frame

      輸出:


      # 給一整列賦值frame["debt"] = 1000frame

      輸出:

      # 對整行賦值frame.loc["six"] = np.NaNframe

      輸出:

      4.4 獲取columns和index

      # 獲取columns名frame.columns
      輸出:Index(['year', 'city', 'population', 'debt'], dtype='object')
      # 獲取index名frame.index

      輸出:Index(['one', 'two', 'three', 'four', 'five', 'six'], dtype='object')

      # 輸出columns名for name in frame.columns:print(name)

      輸出:

      4.5 用Series指定Dataframe要修改的值

                 用Series來指定需要修改的index以及相應(yīng)的value,沒有指定的默認用NaN。

      val = pd.Series([100, 200, 300], index=['two', 'three', 'four'])frame["debt"] = val * 1000frame

      輸出:

      4.6 給index與columns指定名字

      frame.index.name = "row"frame.columns.name = "columns"frame

      輸出:

      4.6 把Dataframe轉(zhuǎn)換成ndarray

              有時候某些操作需要對數(shù)據(jù)進行裝換numpy.ndarray類型才能進行處理,所以要用values對Dataframe進行轉(zhuǎn)換或者as_matrix函數(shù)。

      df.values

      輸出:

      # 判定類型type(df.values)

      輸出:numpy.ndarray

      # 另一個方法df.as_matrix()

      輸出:

      4.7 Dataframe刪除操作

      data = DataFrame(np.arange(16).reshape((4,4)),index = ['Ohio','Colorado','Utah','New York'],columns = ['one','two','three','four'])print(data)#放一個標量就刪除一行或一列,放一個數(shù)組就刪除一組行或者一組列print(data.drop(['Colorado','Ohio']))#axis=0:從上到下,沿著行的方向操作,axis=1:從左到右,沿著列的方向操作print(data.drop('two',axis=1))print(data.drop(['two','four'],axis=1))

      輸出:

      4.8 統(tǒng)計描述

      df = DataFrame([[1.4, np.nan], [7.1, -4.5], [np.nan, np.nan], [0.75, -1.3]],index=['a', 'b', 'c', 'd'],columns=['one', 'two'])print(df)# 每一列的統(tǒng)計信息(自己嘗試一下非數(shù)值型變量統(tǒng)計結(jié)果是什么?)df.describe()

      輸出:
      # get index objectobj = pd.Series(range(3), index=["a", "b", "c"])index = obj.indexindex

      5. index 

      5.1 index object

      obj = pd.Series([4.5, 2.6, -1.8, 9.4], index=["d", "b", "a", "c"])obj

      輸出:Index(['a', 'b', 'c'], dtype='object')

      5.2 index 一些操作

      # 獲取index元素index[1:]

      輸出:Index(['b', 'c'], dtype='object')

      # index的值是不能被更改的# index[0] = 6
      # 構(gòu)造indexindex = pd.Index(np.arange(3))index

      輸出:Int64Index([0, 1, 2], dtype='int64')

      # index的使用obj2 = pd.Series([2,5,7], index=index)obj2

      輸出:

      # 判斷index元素obj2.index is index

      輸出:True

      # 注意與上面的區(qū)別obj2.index is np.arange(3)

      輸出:False

      obj2.index == np.arange(3)

      輸出:array([ True, True, True], dtype=bool)

      # 判斷index是否存在pop = {'Nanjing': {2017: 1000, 2018:1100},'Guangzhou': {2016:800, 2017:850, 2018:880}}frame3 = pd.DataFrame(pop)print(frame3)print("Shanghai" in frame3.columns)

      輸出:

      2017 in frame3.index

      輸出:True

      5.3 index 索引與切片

      # 索引,按照index的元素進行索引obj = pd.Series(range(3), index=["a", "b", "c"])obj["a"]

      輸出:0

      # 使用index默認的數(shù)字進行索引obj[[1,2]]

      輸出:

      # 按照bool值進行索引obj[obj<2]

      輸出:

      # 切片方式obj["b":"c"]

      輸出:

      obj["b":]

      輸出:

      5.4 DataFrame 的index

      cars = pd.Series({"Beijing": 300000, "Shanghai": 350000, "Shenzhen": 300000,                 "Tianjian": 200000, "Guangzhou": 250000, "Chongqing": 150000})cities = {"Shanghai": 90000, "Foshan": 4500, "Dongguan": 5500, "Beijing": 6600, "Nanjing": 8000, "Lanzhou": None}apts = pd.Series(cities, name="price")df = pd.DataFrame({"price": apts, "cars": cars})df

      輸出:

      # 通過index獲取元素,沒有的列輸出NaNdf.loc["Beijing":"Guangzhou", ["price", "other"]]

      輸出:

      # 切片獲取df.iloc[2:4, 1:3]

      輸出:

      注:loc與iloc的區(qū)別,loc可以用名字進行選擇,iloc用index數(shù)字進行選擇

      5.4 DataFrame 條件選擇

      5.4 DataFrame 的index

      輸出:

      # 條件選擇df[df.price > 5000]

      輸出:

      5.5 Series index重排    

          把一個Series或者DataFrame按照新的index順序進行重排

      obj = pd.Series([4.5, 2.6, -1.8, 9.4], index=["d", "b", "a", "c"])obj

      輸出:

      # 對index進行重排obj.reindex(["a", "b", "c", "d", "e"])

      輸出:

      5.6 Series reindex對NaN進行填充

      把一個Series或者DataFrame按照新的index順序進行重排

      obj.reindex(["a", "b", "c", "d", "e"], fill_value=obj.mean())

      輸出:


      # 如果為空,填充前面index的值obj3.reindex(range(6), method="ffill")

      輸出:

      # 獲取后面的值,進行填充obj3.reindex(range(6), method="bfill") # backward fill

      輸出:

      5.7 DataFrame index重排

      data = {'city': ['Shanghai', 'Nanjing', 'Lanzhou', 'Shangsha', 'Guizhou', 'Xian'],'year': [2017,2018,2017,2018,2018,2017],'population': [2100, 600, 800, 700, 560, 900]}frame = pd.DataFrame(data, columns=["year", "city", "population", "debt"],index=["one", "two", "three", "four", "five", "six"])frame2 = frame.reindex(["one", "three", "four", "eight"])frame2

      輸出:

      # 對列進行重排frame.reindex(columns=["city", "year", "population"])

      輸出:


      5.8 對index進行刪除

          對于使用drop刪除index并不能真正,只是刪除之后,返回剩余的部分。

      obj3 = pd.Series(["blue", "red", "yello"], index=[1,3,5])obj4 = obj3.drop(5)print(obj4)obj3

      輸出:

      obj3.drop([3,5])

      輸出:

      # 對dataframe進行dropdata = {'city': ['Shanghai', 'Nanjing', 'Lanzhou', 'Shangsha', 'Guizhou', 'Xian'],'year': [2017,2018,2017,2018,2018,2017],'population': [2100, 600, 800, 700, 560, 900]}frame = pd.DataFrame(data, columns=["year", "city", "population", "debt"],index=["one", "two", "three", "four", "five", "six"])frame.drop(["debt", "year"], axis=1)

      輸出:

      5.8 Series多層index

      # Series的多層index# 構(gòu)造多層indexdata = pd.Series(np.random.randn(10), index=                 [['a','a','a','b','b','c','c','c','d','d'],                  [1,2,3,1,2,1,2,3,1,2]])print(data)

      輸出:

      # 獲取index objectdata.index

      輸出:

      # 通過index獲取元素data.b

      輸出:

      # 切片方式data["b":"c"]

      輸出:

      # 通過默認的indexdata[2:5]

      輸出:

      5.9 hierarchical indexing和DataFrame轉(zhuǎn)換

      可以通過unstack和stack進行轉(zhuǎn)換。

      type(data.unstack())
      輸出:data.unstack().stack()
      data.unstack().stack()

      輸出:

      5.10 hierarchical indexing & DataFrame

      frame = pd.DataFrame(np.arange(12).reshape((4,3)),index = [['a','a','b','b'], [1,2,1,2]],columns = [['xiaoming', 'lisi', 'lisi'], ['one', 'tow', 'three']])frame

      輸出:


      # 取值frame.loc["a", 1]["lisi"]["tow"]

      輸出:1

      6. CSV文件讀取

      6.1 默認讀取方式

      goog = pd.read_csv("data/GOOG.csv")goog.head() #輸出前幾個

      輸出:


      6.2 指定index讀取

      # 讀進來的時候設(shè)置index,聲明哪里列是日期goog = pd.read_csv("data/GOOG.csv", index_col=0, parse_dates=[0])goog.head()

      輸出:

      # 獲取indexgoog.index

      輸出:'2004-08-19', '2004-08-20', '2004-08-23', '2004-08-24'..........

      6.3  CSV文件存儲

           使用to_csv函數(shù)。

      # 以\t的方式進行分隔df.to_csv("data/test.tsv", sep="\t")

      6. 作圖

      # 根據(jù)上面的數(shù)據(jù)作圖# 把圖片輸出到當前界面%matplotlib inlinegoog["Adj Close"].plot()

      輸出:

      # 1/1/2010", periods=1000):從這個日期開始,往后推一千天ts = pd.Series(np.random.randn(1000)*100, index=pd.date_range("1/1/2010", periods=1000))ts = ts.cumsum()ts.plot()

      輸出:

      # dataframe直接繪制圖像df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))df = df.cumsum()df.plot()

      輸出:

      # 繪制柱狀圖df.iloc[5].plot(kind="bar")

      輸出:



      # 狀圖圖# 橫著畫df.head().plot.barh(stacked=True)# 豎著 畫# df.head().plot.bar(stacked=True)

      輸出:


      對于機器學習之pandas的應(yīng)用上節(jié)到這里結(jié)束了,對于跟著這個教程學習的同學,一定要多操作,多動手。

        本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多