<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          pandas入門:Series、DataFrame、Index基本操作都有了!

          共 2758字,需瀏覽 6分鐘

           ·

          2020-09-18 09:06


          導(dǎo)讀:pandas是一款開放源碼的BSD許可的Python庫(kù)。它基于NumPy創(chuàng)建,為Python編程語(yǔ)言提供了高性能的、易于使用的數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)分析工具。


          pandas應(yīng)用領(lǐng)域廣泛,包括金融、經(jīng)濟(jì)、統(tǒng)計(jì)、分析等學(xué)術(shù)和商業(yè)領(lǐng)域。本文將介紹pandas中Series、DataFrame、Index等常用類的基本用法。

          作者:李明江 張良均 周東平 張尚佳

          來(lái)源:大數(shù)據(jù)DT(ID:hzdashuju)





          pandas提供了眾多類,可滿足不同的使用需求,其中常用的類如下所示。

          • Series:基本數(shù)據(jù)結(jié)構(gòu),一維標(biāo)簽數(shù)組,能夠保存任何數(shù)據(jù)類型
          • DataFrame:基本數(shù)據(jù)結(jié)構(gòu),一般為二維數(shù)組,是一組有序的列
          • Index:索引對(duì)象,負(fù)責(zé)管理軸標(biāo)簽和其他元數(shù)據(jù)(比如軸名稱)
          • groupby:分組對(duì)象,通過(guò)傳入需要分組的參數(shù)實(shí)現(xiàn)對(duì)數(shù)據(jù)分組
          • Timestamp:時(shí)間戳對(duì)象,表示時(shí)間軸上的一個(gè)時(shí)刻
          • Timedelta:時(shí)間差對(duì)象,用來(lái)計(jì)算兩個(gè)時(shí)間點(diǎn)的差值

          在這6個(gè)類中,Series、DataFrame和Index是使用頻率最高的類。


          01 Series

          Series由一組數(shù)據(jù)以及一組與之對(duì)應(yīng)的數(shù)據(jù)標(biāo)簽(即索引)組成。Series對(duì)象可以視作一個(gè)NumPy的ndarray,因此許多NumPy庫(kù)函數(shù)可以作用于Series。

          1. 創(chuàng)建Series

          創(chuàng)建Series對(duì)象的函數(shù)是Series,它的主要參數(shù)是data和index,其基本語(yǔ)法格式如下。

          class?pandas.Series(data=None,?index=None,?dtype=None,?name=None,?copy=False,?fastpath=False)

          Series函數(shù)常用的參數(shù)及其說(shuō)明如下所示。

          • data:接收array或dict。表示接收的數(shù)據(jù)。默認(rèn)為None
          • index:接收array或list。表示索引,它必須與數(shù)據(jù)長(zhǎng)度相同。默認(rèn)為None
          • name:接收string或list。表示Series對(duì)象的名稱。默認(rèn)為None

          Series本質(zhì)上是一個(gè)ndarray,通過(guò)ndarray創(chuàng)建Series對(duì)象,如代碼清單6-1所示。

          • 代碼清單6-1 通過(guò)ndarray創(chuàng)建Series

          import?pandas?as?pd
          import?numpy?as?np
          print('通過(guò)ndarray創(chuàng)建的Series為:\n',
          ??????pd.Series(np.arange(5),?index?=?['a',?'b',?'c',?'d',?'e'],?name?=?'ndarray'))

          輸出:


          通過(guò)ndarray創(chuàng)建的Series為:
          a????0
          b????1
          c????2
          d????3
          e????4
          Name:?ndarray,?dtype:?int32

          若數(shù)據(jù)存放于一個(gè)dict中,則可以通過(guò)dict創(chuàng)建Series,此時(shí)dict的鍵名(key)作為Series的索引,其值會(huì)作為Series的值,因此無(wú)須傳入index參數(shù)。通過(guò)dict創(chuàng)建Series對(duì)象,如代碼清單6-2所示。

          • 代碼清單6-2 通過(guò)dict創(chuàng)建Series

          dit?=?{'a':?0,?'b':?1,?'c':?2,?'d':?3,?'e':?4}
          print('通過(guò)dict創(chuàng)建的Series為:\n',?pd.Series(dit))

          輸出:

          通過(guò)dict創(chuàng)建的Series為:
          a????0
          b????1
          c????2
          d????3
          e????4
          dtype:?int64

          通過(guò)list創(chuàng)建Series,類似于通過(guò)ndarray創(chuàng)建Series,如代碼清單6-3所示。

          • 代碼清單6-3 通過(guò)list創(chuàng)建Series

          list1?=?[0,?1,?2,?3,?4]
          print('通過(guò)list創(chuàng)建的Series為:\n',?pd.Series(list1,?index?=?['a',?'b',?'c',?'d',?'e'],?name?=?'list'))

          輸出:

          通過(guò)list創(chuàng)建的Series為:
          a????0
          b????1
          c????2
          d????3
          e????4
          Name:?list,?dtype:?int64

          Series擁有8個(gè)常用屬性,如下所示。

          • values:以ndarray的格式返回Series對(duì)象的所有元素
          • index:返回Series對(duì)象的索引
          • dtype:返回Series對(duì)象的數(shù)據(jù)類型
          • shape:返回Series對(duì)象的形狀
          • nbytes:返回Series對(duì)象的字節(jié)數(shù)
          • ndim:返回Series對(duì)象的維度
          • size:返回Series對(duì)象的個(gè)數(shù)
          • T:返回Series對(duì)象的轉(zhuǎn)置

          訪問(wèn)Series的屬性,如代碼清單6-4所示。

          • 代碼清單6-4 訪問(wèn)Series的屬性

          series?=?pd.Series(list1,?index?=?['a',?'b',?'c',?'d',?'e'],?name?=?'list')
          print('數(shù)組形式返回Series為:',?series.values)

          #輸出:數(shù)組形式返回Series為:?[0 1 2 3 4]

          print('Series的Index為:',?series.index)

          #輸出:Series的Index為:Index(['a', 'b', 'c', 'd', 'e'], dtype='object')

          print('Series的形狀為:',?series.shape)

          #輸出:Series的形狀為:?(5,)

          print('Series的維度為:',?series.ndim)

          #輸出:Series的維度為:1

          2. 訪問(wèn)Series數(shù)據(jù)

          索引與切片是Series最常用操作之一。通過(guò)索引位置訪問(wèn)Series的數(shù)據(jù)與ndarray相同,如代碼清單6-5所示。

          • 代碼清單6-5 通過(guò)索引位置訪問(wèn)Series數(shù)據(jù)子集

          print('Series位于第1位置的數(shù)據(jù)為:',?series[0])

          輸出:

          Series位于第1位置的數(shù)據(jù)為:?0

          相比ndarray,通過(guò)索引名稱(標(biāo)簽)也可以訪問(wèn)Series數(shù)據(jù),如代碼清單6-6所示。

          • 代碼清單6-6 通過(guò)索引名稱訪問(wèn)Series數(shù)據(jù)

          print('Series中Index為a的數(shù)據(jù)為:',?series['a'])

          輸出:

          Series中Index為a的數(shù)據(jù)為:?0

          此外,也可通過(guò)bool類型的Series、list或array訪問(wèn)Series數(shù)據(jù),如代碼清單6-7所示。

          • 代碼清單6-7 通過(guò)bool數(shù)組訪問(wèn)Series數(shù)據(jù)

          bool?=?(series?4)
          print('bool類型的Series為:\n',?bool)

          輸出:


          bool類型的Series為:
          a?????True
          b?????True
          c?????True
          d?????True
          e????False
          Name:?list,?dtype:?bool

          print('通過(guò)bool數(shù)據(jù)訪問(wèn)Series結(jié)果為:\n',?series[bool])

          輸出:

          通過(guò)bool數(shù)據(jù)訪問(wèn)Series結(jié)果為:
          a????0
          b????1
          c????2
          d????3
          Name:?list,?dtype:?int64

          3. 更新、插入和刪除

          更新Series的方法十分簡(jiǎn)單,采用賦值的方式對(duì)指定索引標(biāo)簽(或位置)對(duì)應(yīng)的數(shù)據(jù)進(jìn)行修改即可,如代碼清單6-8所示。

          • 代碼清單6-8 更新Series

          #?更新元素
          series['a']?=?3
          print('更新后的Series為:\n',?series)

          輸出:

          更新后的Series為:
          a????3
          b????1
          c????2
          d????3
          e????4
          Name:?list,?dtype:?int64

          類似list,通過(guò)append方法能夠在原Series上插入(追加)新的Series。若只在原Series上插入單個(gè)值,則采用賦值方式即可,如代碼清單6-9所示。

          • 代碼清單6-9 追加Series和插入單個(gè)值

          series1?=?pd.Series([4,?5],?index?=?['f',?'g'])
          #?追加Series
          print('在series插入series1后為:\n',?series.append(series1))

          輸出:

          在series插入series1后為:
          a????3
          b????1
          c????2
          d????3
          e????4
          f????4
          g????5
          dtype:?int64

          #?新增單個(gè)數(shù)據(jù)
          series1['h']?=?7
          print('在series1插入單個(gè)數(shù)據(jù)后為:\n',?series1)

          輸出:

          在series1插入單個(gè)數(shù)據(jù)后為:
          f????4
          g????5
          h????7
          dtype:?int64

          一般使用drop方法刪除Series元素,它接收被刪除元素對(duì)應(yīng)的索引,inplace=True表示對(duì)原Series起作用,如代碼清單6-10所示。

          • 代碼清單6-10 刪除Series元素

          #?刪除數(shù)據(jù)
          series.drop('e',?inplace?=?True)
          print('刪除索引e對(duì)應(yīng)數(shù)據(jù)后的series為:\n',?series)

          輸出:


          刪除索引e對(duì)應(yīng)數(shù)據(jù)后的series為:
          a????3
          b????1
          c????2
          d????3
          Name:?list,?dtype:?int64


          02 DataFrame

          DataFrame是pandas基本數(shù)據(jù)結(jié)構(gòu),類似數(shù)據(jù)庫(kù)中的表。DataFrame既有行索引,也有列索引,它可以看作Series組成的dict,每個(gè)Series看作DataFrame的一個(gè)列。

          1. 創(chuàng)建DataFrame

          DataFrame函數(shù)用于創(chuàng)建DataFrame對(duì)象,其基本語(yǔ)法格式如下。

          class?pandas.DataFrame(data=None,?index=None,?columns=None,?dtype=None,?copy=False)

          DataFrame函數(shù)常用的參數(shù)及其說(shuō)明如下所示。

          • data:接收ndarray,dict,list或DataFrame。表示輸入數(shù)據(jù)。默認(rèn)為None
          • index:接收Index,ndarray。表示索引。默認(rèn)為None
          • columns:接收Index,ndarray。表示列標(biāo)簽(列名)。默認(rèn)為None

          創(chuàng)建DataFrame的方法有很多,常見(jiàn)的一種是傳入一個(gè)由等長(zhǎng)list或ndarray組成的dict。若沒(méi)有傳入columns參數(shù),則傳入的dict的鍵會(huì)被當(dāng)作列名,如代碼清單6-11所示。

          • 代碼清單6-11 通過(guò)dict創(chuàng)建DataFrame

          dict1?=?{'col1':?[0,?1,?2,?3,?4],?'col2':?[5,?6,?7,?8,?9]}
          print('通過(guò)dict創(chuàng)建的DataFrame為:\n',?pd.DataFrame(dict1,?index?=?['a',?'b',?'c',?'d',?'e']))

          輸出:

          通過(guò)dict創(chuàng)建的DataFrame為:
          ????col1??col2
          a?????0?????5
          b?????1?????6
          c?????2?????7
          d?????3?????8
          e?????4?????9

          通過(guò)list或ndarray也可創(chuàng)建DataFrame,如代碼清單6-12所示。

          • 代碼清單6-12 通過(guò)list創(chuàng)建DataFrame

          list2?=?[[0,?5],?[1,?6],?[2,?7],?[3,?8],?[4,?9]]
          print('通過(guò)list創(chuàng)建的DataFrame為:\n',
          ??????pd.DataFrame(list2,?index?=?['a',?'b',?'c',?'d',?'e'],?columns?=?['col1',?'col2']))

          輸出:

          通過(guò)list創(chuàng)建的DataFrame為:
          ????col1??col2
          a?????0?????5
          b?????1?????6
          c?????2?????7
          d?????3?????8
          e?????4?????9

          由于DataFrame是二維數(shù)據(jù)結(jié)構(gòu),包含列索引(列名),因此較Series有更多的屬性。DataFrame常用的屬性及其說(shuō)明如下所示。

          • values:以ndarray的格式返回DataFrame對(duì)象的所有元素
          • index:返回DataFrame對(duì)象的Index
          • columns:返回DataFrame對(duì)象的列標(biāo)簽
          • dtypes:返回DataFrame對(duì)象的數(shù)據(jù)類型
          • axes:返回DataFrame對(duì)象的軸標(biāo)簽
          • ndim:返回DataFrame對(duì)象的軸尺寸數(shù)
          • size:返回DataFrame對(duì)象的個(gè)數(shù)
          • shape:返回DataFrame對(duì)象的形狀

          訪問(wèn)創(chuàng)建的DataFrame的常用屬性,如代碼清單6-13所示。

          • 代碼清單6-13 訪問(wèn)DataFrame的屬性

          df?=?pd.DataFrame({'col1':?[0,?1,?2,?3,?4],?'col2':?[5,?6,?7,?8,?9]},
          ???????????????????index?=?['a',?'b',?'c',?'d',?'e'])
          print('DataFrame的Index為:',?df.index)

          #輸出:DataFrame的Index為:Index(['a', 'b', 'c', 'd', 'e'], dtype='object')

          print('DataFrame的列標(biāo)簽為:',?df.columns)

          #輸出:DataFrame的列標(biāo)簽為:Index(['col1', 'col2'], dtype='object')

          print('DataFrame的軸標(biāo)簽為:',?df.axes)

          #輸出:DataFrame的軸標(biāo)簽為:?[Index(['a', 'b', 'c', 'd', 'e'], dtype='object'), Index(['col1', 'col2'], dtype='object')]

          print('DataFrame的維度為:',?df.ndim)

          #輸出:DataFrame的維度為:2

          print('DataFrame的形狀為:',?df.shape)

          #輸出:DataFrame的形狀為:?(5, 2)

          2. 訪問(wèn)DataFrame首尾數(shù)據(jù)

          head和tail方法用于訪問(wèn)DataFrame前n行和后n行數(shù)據(jù),默認(rèn)返回5行數(shù)據(jù),如代碼清單6-14所示。

          • 代碼清單6-14 訪問(wèn)DataFrame前后n行數(shù)據(jù)

          print('默認(rèn)返回前5行數(shù)據(jù)為:\n',?df.head())????

          輸出:


          默認(rèn)返回前5行數(shù)據(jù)為:
          ????col1??col2
          a?????0?????5
          b?????1?????6
          c?????2?????7
          d?????3?????8
          e?????4?????9????

          print('返回后3行數(shù)據(jù)為:\n',?df.tail(3))

          輸出:


          返回后3行數(shù)據(jù)為:
          ????col1??col2
          c?????2?????7
          d?????3?????8
          e?????4?????9

          3. 更新、插入和刪除

          類似Series,更新DataFrame列也采用賦值的方法,對(duì)指定列賦值即可,如代碼清單6-15所示。

          • 代碼清單6-15 更新DataFrame

          #?更新列
          df['col1']?=?[10,?11,?12,?13,?14]
          print('更新列后的DataFrame為:\n',?df)

          輸出:

          更新列后的DataFrame為:
          ????col1??col2
          a????10?????5
          b????11?????6
          c????12?????7
          d????13?????8
          e????14?????9

          插入列也可以采用賦值方法,如代碼清單6-16所示。

          • 代碼清單6-16 采用賦值的方法插入列

          #?插入列
          df['col3']?=?[15,?16,?17,?18,?19]
          print('插入列后的DataFrame為:\n',?df)

          輸出:

          插入列后的DataFrame為:
          ????col1??col2??col3
          a????10?????5????15
          b????11?????6????16
          c????12?????7????17
          d????13?????8????18
          e????14?????9????19

          刪除列的方法有多種,如del、pop、drop等。常用的是drop方法,它可以刪除行或者列,基本語(yǔ)法格式如下。

          DataFrame.drop(labels,?axis=0,?level=None,?inplace=False,?errors='raise')

          drop方法常用的參數(shù)及其說(shuō)明如下所示。

          • labels:接收string或array。表示刪除的行或列的標(biāo)簽。無(wú)默認(rèn)值
          • axis:接收0或1。表示執(zhí)行操作的軸向,其中0表示刪除行,1表示刪除列。默認(rèn)為0
          • levels:接收int或者索引名。表示索引級(jí)別。默認(rèn)為None
          • inplace:接收bool。表示操作是否對(duì)原數(shù)據(jù)生效。默認(rèn)為False

          使用drop方法刪除數(shù)據(jù),如代碼清單6-17所示。

          • 代碼清單6-17 使用drop方法刪除數(shù)據(jù)

          #?刪除列
          df.drop(['col3'],?axis?=?1,?inplace?=?True)
          print('刪除col3列后的DataFrame為:\n',?df)

          輸出:

          刪除col3列后的DataFrame為:
          ????col1??col2
          a????10?????5
          b????11?????6
          c????12?????7
          d????13?????8
          e????14?????9

          #?刪除行
          df.drop('a',?axis?=?0,?inplace?=?True)
          print('刪除a行后的DataFrame為:\n',?df)

          輸出:

          刪除a行后的DataFrame為:
          ????col1??col2
          b????11?????6
          c????12?????7
          d????13?????8
          e????14?????9


          03 Index

          Index對(duì)象為其余pandas對(duì)象存儲(chǔ)軸標(biāo)簽、管理軸標(biāo)簽和其他元數(shù)據(jù)(如軸名稱)。創(chuàng)建Series或DataFrame等對(duì)象時(shí),索引都會(huì)被轉(zhuǎn)換為Index對(duì)象。主要Index對(duì)象及其說(shuō)明如下所示。

          • Index:一般的Index對(duì)象
          • MultiIndex:層次化Index對(duì)象
          • DatetimeIndex:Timestamp索引對(duì)象
          • PeriodIndex:Period索引對(duì)象

          1. 創(chuàng)建Index

          Index對(duì)象可以通過(guò)pandas.Index()函數(shù)創(chuàng)建,也可以通過(guò)創(chuàng)建數(shù)據(jù)對(duì)象Series、DataFrame時(shí)接收index(或column)參數(shù)創(chuàng)建,前者屬于顯式創(chuàng)建,后者屬于隱式創(chuàng)建。隱式創(chuàng)建中,通過(guò)訪問(wèn)index(或針對(duì)DataFrame的column)屬性即得到Index。創(chuàng)建的Index對(duì)象不可修改,保證了Index對(duì)象在各個(gè)數(shù)據(jù)結(jié)構(gòu)之間的安全共享。Series的索引是一個(gè)Index對(duì)象。訪問(wèn)Series索引,如代碼清單6-18所示。

          • 代碼清單6-18 訪問(wèn)Series索引

          print('series的Index為?:\n',?series.index)

          輸出:

          series的Index為?:
          ?Index(['a',?'b',?'c',?'d'],?dtype='object')

          Index對(duì)象常用的屬性及其說(shuō)明如下所示。

          • is_monotonic:當(dāng)各元素均大于前一個(gè)元素時(shí),返回True
          • is_unique:當(dāng)Index沒(méi)有重復(fù)值時(shí),返回True

          訪問(wèn)Index屬性,如代碼清單6-19所示。

          • 代碼清單6-19 訪問(wèn)Index屬性

          print('series中Index各元素是否大于前一個(gè):',?series.index.is_monotonic)

          #輸出:series中Index各元素是否大于前一個(gè):True

          print('series中Index各元素是否唯一:',?series.index.is_unique)

          #輸出:series中Index各元素是否唯一:True

          2. 常用方法

          Index對(duì)象的常用方法及其說(shuō)明如下所示。

          • append:連接另一個(gè)Index對(duì)象,產(chǎn)生一個(gè)新的Index
          • difference:計(jì)算兩個(gè)Index對(duì)象的差集,得到一個(gè)新的Index
          • intersection:計(jì)算兩個(gè)Index對(duì)象的交集
          • union:計(jì)算兩個(gè)Index對(duì)象的并集
          • isin:計(jì)算一個(gè)Index是否在另一個(gè)Index,返回bool數(shù)組
          • delete:刪除指定Index的元素,并得到新的Index
          • drop:刪除傳入的值,并得到新的Index
          • insert:將元素插入到指定Index處,并得到新的Index
          • unique:計(jì)算Index中唯一值的數(shù)組

          應(yīng)用Index對(duì)象的常用方法如代碼清單6-20所示。

          • 代碼清單6-20 應(yīng)用Index對(duì)象的常用方法

          index1?=?series.index
          index2?=?series1.index
          print('index1連接index2后結(jié)果為:\n',?index1.append(index2))

          #輸出:index1連接index2后結(jié)果為:
          #?Index(['a',?'b',?'c',?'d',?'f',?'g',?'h'],?dtype='object')

          print('index1與index2的差集為:',?index1.difference(index2))

          #輸出:index1與index2的差集為:Index(['a', 'b', 'c', 'd'], dtype='object')

          print('index1與index2的交集為:',?index1.intersection(index2))

          #輸出:index1與index2的交集為:Index([], dtype='object')

          print('index1與index2的并集為:\n',?index1.union(index2))

          #輸出:index1與index2的并集為:
          #?Index(['a',?'b',?'c',?'d',?'f',?'g',?'h'],?dtype='object')

          print('index1中的元素是否在index2中:',?index1.isin(index2))

          #輸出:index1中的元素是否在index2中:?[False False False False]



          關(guān)于作者:李明江,資深大數(shù)據(jù)專家,貴州省計(jì)算機(jī)學(xué)會(huì)常務(wù)理事,黔南州大數(shù)據(jù)專家委員會(huì)委員,黔南州計(jì)算機(jī)學(xué)會(huì)會(huì)長(zhǎng),黔南州教育信息化建設(shè)專家?guī)鞂<遥厦褡鍘煼秾W(xué)院計(jì)算機(jī)與信息學(xué)院院長(zhǎng),全國(guó)高校大數(shù)據(jù)教育聯(lián)盟理事。
          張良均,資深大數(shù)據(jù)挖掘與分析專家、模式識(shí)別專家、AI技術(shù)專家。有10余年大數(shù)據(jù)挖掘與分析經(jīng)驗(yàn),擅長(zhǎng)Python、R、Hadoop、Matlab等技術(shù)實(shí)現(xiàn)的數(shù)據(jù)挖掘與分析,對(duì)機(jī)器學(xué)習(xí)等AI技術(shù)驅(qū)動(dòng)的數(shù)據(jù)分析也有深入研究。




          相關(guān)閱讀:



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

          手機(jī)掃一掃分享

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

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  麻豆成人在线观看 | 欧美操逼系列 | 俺去也亚洲地区 | 一级黄色免费视频网站 | 色五月婷婷在线播放 |