pandas基礎(1)_Series和DataFrame


1:pandas簡介

               Python Data Analysis Library 或 pandas 是基於NumPy 的一種工具,該工具是為了解決數據分析任務而創建的。Pandas 納入了大量庫和一些標准的數據模型,提供了高效地操作大型數據集所需的工具。pandas提供了大量能使我們快速便捷地處理數據的函數和方法。你很快就會發現,它是使Python成為強大而高效的數據分析環境的重要因素之一。

2:Series和DataFrame()

 1:Series:是一種類似於一維數組的對象,由下面兩個部分組成:

              Values:一組數據值(ndarray)類型

              Index:相關的數據索引標簽、

 2:Series的創建方法

1)由列表和numpy數組創建

 

>>> s=Series([1,3,4,5])

 

>>> s

 

0    1

 

1    3

 

2    4

 

3    5

 

dtype: int64

 

>>> #會自動將索引打印出來

 

>>> s.index=list('abcd')

 

>>> s

 

a    1

 

b    3

 

c    4

 

d    5

 

dtype: int64

 

>>> #使索引變成了字母abcd

 

>>> s = Series([1,2,3,4],index=['mike','sana','luna','la'])

 

>>> s

 

mike    1

 

sana    2

 

luna    3

 

la      4

 

dtype: int64

 

>>> #Series里面的數據是一維的

 

(2)由字典創建

 

>>> #Series里面的數據是一維的

 

>>> s1=Series({'a':1,'b':2})

 

>>> s1

 

a    1

 

b    2

 

dtype: int64

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

 

3:Series的索引

(1)顯示索引

>>> s=Series(np.random.random(10),index=list('abcdefghig'))

>>> s

a    0.370897

b    0.993346

c    0.148304

d    0.456316

e    0.365877

f    0.424124

g    0.685219

h    0.694954

i    0.563674

g    0.982072

dtype: float64

>>> s['a']#使用index作為索引值

0.37089735452082695

>>> s.loc['a']#使用,loc方法顯示獲取索引

0.37089735452082695

>>> s[0]

0.37089735452082695

>>> s.loc[0]#因為是顯示索引會報錯

 

Traceback (most recent call last):

  File "<pyshell#59>", line 1, in <module>

    s.loc[0]#因為是顯示索引會報錯

>>> s.iloc[0]

0.37089735452082695

>>> #因為此時是隱式索引所以不會報錯,,隱式索引默認為0,1,2.......

>>> s.loc['a':'e']

a    0.370897

b    0.993346

c    0.148304

d    0.456316

e    0.365877

dtype: float64

>>> #切片處理

>>>

Series的基本概念

  可以把Series看成一個定長的有序字典

可以通過shapesizeindexvalues,,等得到series的屬性

>>> s.shape

(10L,)

>>> s.size

10

>>> s.index

Index([u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', u'i', u'g'], dtype='object')

>>> s.values

array([0.37089735, 0.99334641, 0.14830394, 0.45631575, 0.36587742,

       0.42412389, 0.68521869, 0.69495357, 0.56367448, 0.98207233])

>>> #Seriesvalues,就是一個ndrray包含關系,升級的關系,有了索引更方便

>>> s.shape

(10L,)

>>> s.head

<bound method Series.head of a    0.370897

b    0.993346

c    0.148304

d    0.456316

e    0.365877

f    0.424124

g    0.685219

h    0.694954

i    0.563674

g    0.982072

dtype: float64>

>>> s.tail

<bound method Series.tail of a    0.370897

b    0.993346

c    0.148304

d    0.456316

e    0.365877

f    0.424124

g    0.685219

h    0.694954

i    0.563674

g    0.982072

dtype: float64>

>>> #Series對象本身實例有一個name屬性

>>> s.name="列名"

>>> s

a    0.370897

b    0.993346

c    0.148304

d    0.456316

e    0.365877

f    0.424124

g    0.685219

h    0.694954

i    0.563674

g    0.982072

Name: ????, dtype: float64

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、’

4:Series的運算

>>> s.add(10,fill_value=0)#在進行算數運算時,如果包含nan ,那么fill_value默認設置為fill_value

a    10.370897

b    10.993346

c    10.148304

d    10.456316

e    10.365877

f    10.424124

g    10.685219

h    10.694954

i    10.563674

g    10.982072

Name: ????, dtype: float64

>>> #Series之間的運算

>>> s1=Series([2,4,7,9],index=[0,1,2,3])

>>> s2=Series([1,2,3,4],index=[2,3,4,5])

>>> s1+s2#Series索引值,進行相加時,就是索引值進行相加

0     NaN

1     NaN

2     8.0

3    11.0

4     NaN

5     NaN

dtype: float64

>>> #要保留所有的index,必須使用.add()函數

>>> s1.add(s2,fill_value=0)

0     2.0

1     4.0

2     8.0

3    11.0

4     3.0

5     4.0

dtype: float64

>>> s1.add(s2)

0     NaN

1     NaN

2     8.0

3    11.0

4     NaN

5     NaN

dtype: float64

>>> #因為不同的Series存在不同的索引值,所以當對應另一個Series不存在該索引時要把fill_value定義為0

>>> s=Series([1,2,None])

>>> nd=np.array([1,2,None])

>>> s.sum()

3.0

>>> nd.sum()#會報錯,因為有非數字,沒辦法進行計算

 

Traceback (most recent call last):

  File "<pyshell#89>", line 1, in <module>

    nd.sum()#會報錯,因為有非數字

  File "E:\Python\lib\site-packages\numpy\core\_methods.py", line 32, in _sum

    return umr_sum(a, axis, dtype, out, keepdims)

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

>>> #ndarray中如果有nan,沒有辦法進行計算,而Series可以

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

5:DataFrame的定義

 

        DataFrame是一個【表格型】的數據結構,可以看做是【由Series組成的字典】公用一個索引。DataFrame由按一定順序排列的多列數據。設計初衷是將Series的使用場景從一維擴展到多維,DataFrame既有行索引,也有列索引

 

行索引:index

 

列索引:column

 

值:valuesnumpy的二維數組)

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

6:DataFrame的創建:

 

  最常用的方法是由一個字典來創建,DataFrame以字典的建作為每一{}的名稱。以字典的值作為每一列

 

此外,dataframeSeries一樣會自動為每一行加索引,相應值為nan

 

>>> df= DataFrame({'height':[175,180,169,188],'age':np.random.randint(18,25,size=4),'sex':['boy','girl','boy','girl']})

 

 

 

>>> df

 

   age  height   sex

 

0   22     175   boy

 

1   20     180  girl

 

2   22     169   boy

 

3   20     188  girl

 

>>> df= DataFrame({'height':[175,180,169,188],'age':np.random.randint(18,25,size=4),'sex':['boy','girl','boy','girl']},index=list('ABCD'),columns=['height','age','sex','weight'])

 

>>> df

 

   height  age   sex weight    #weight默認為nan

 

A     175   19   boy    NaN

 

B     180   23  girl    NaN

 

C     169   21   boy    NaN

 

D     188   18  girl    NaN

 

>>> df.shape

 

(4, 4)

 

>>> df.values

 

array([[175L, 19, 'boy', nan],

 

       [180L, 23, 'girl', nan],

 

       [169L, 21, 'boy', nan],

 

       [188L, 18, 'girl', nan]], dtype=object)

 

>>> df.columns

 

Index([u'height', u'age', u'sex', u'weight'], dtype='object')

 

>>> df.index

 

Index([u'A', u'B', u'C', u'D'], dtype='object')

 

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

7:DataFrame的索引

(1)對列進行索引

        。通過類似字典的方式

        。通過屬性的方式

 >>> df['age']

A    19

B    23

C    21

D    18

Name: age, dtype: int32

>>> #檢索列返回值是Series

>>>

>>> df.age

A    19

B    23

C    21

D    18

Name: age, dtype: int32

>>> #對於DataFrame,列名,就相當於屬性,

>>> #DataFrame是統計數據時,用的表格,某一個事物屬性,每個屬性對應Dataframe列名

>>> df['A']#該方法無法檢索行,會報錯

>>> #使用.loc[]index來進行索引

>>> #使用.ix[]來進行索引,(過時)

>>> #使用iloc[]加整數來進行索引

>>> #對於行進行索引,返回值也是Series

>>> df.loc[['A','B']]

   height  age   sex weight

A     175   19   boy    NaN

B     180   23  girl    NaN

>>> #!!!['A','B'],如果檢索多行,返回的數據就是DataFrame

>>> df.loc['A':'C']

   height  age   sex weight

A     175   19   boy    NaN

B     180   23  girl    NaN

C     169   21   boy    NaN

>>> #AC左閉右閉

>>> df['height':'age']#對列是不可以進行切片的

Empty DataFrame

Columns: [height, age, sex, weight]

Index: []

>>> df.iloc[1:3]#隱式索引

   height  age   sex weight

B     180   23  girl    NaN

C     169   21   boy    NaN

>>> #左開右閉

#!!!,DataFrame自身有bug,索引是漢字,有時無法檢索

>>> df['sex']#直接用中括號時,索引表示的是列索引,切片表示的是行切片

A     boy

B    girl

C     boy

D    girl

Name: sex, dtype: object

>>> df['sex']['A':'B']

A     boy

B    girl

Name: sex, dtype: object

>>> df['sex']['A':'B']=['','']

>>> df

   height  age   sex weight

A     175   19    ??    NaN

B     180   23     ?    NaN

C     169   21   boy    NaN

D     188   18  girl    NaN

>>> df.loc['C','height']

169

>>> #檢索行的時候,參數可以是多個

>>> #但是列無法完成該類型的操作

>>> df.values[0,2]

'\xc4\xd0'

>>> '\xc5\xae'#通過坐標進行檢索

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

8:DataFrame的計算

 

de1=DataFrame(np.random.randint(0,150,size=(5,4)),index=['A','B','C','D','E'],columns=['a','b','c','e'])

 

>>> de1

 

     a    b    c    e

 

A  113  143   22   28

 

B  102  120   80  144

 

C   37   36  120   80

 

D  134   82   65   96

 

E   49   51   46   23

 

>>> de2=DataFrame(np.random.randint(0,150,size=(4,4)),index=['A','B','C','D'],columns=['a','b','c','e'])

 

>>> de2

 

     a   b   c    e

 

A   35  13  90   11

 

B   58  63  59   38

 

C   18  56  49  111

 

D  142  24  29   33

 

>>> de2.add(de1)

 

       a      b      c      e

 

A  148.0  156.0  112.0   39.0

 

B  160.0  183.0  139.0  182.0

 

C   55.0   92.0  169.0  191.0

 

D  276.0  106.0   94.0  129.0

 

E    NaN    NaN    NaN    NaN

 

>>> de2.add(de1,fill_value=0)

 

       a      b      c      e

 

A  148.0  156.0  112.0   39.0

 

B  160.0  183.0  139.0  182.0

 

C   55.0   92.0  169.0  191.0

 

D  276.0  106.0   94.0  129.0

 

E   49.0   51.0   46.0   23.0

 

>>> #fillvalue=0可以避免出現nan的情況

 

>>> de1+de2

 

       a      b      c      e

 

A  148.0  156.0  112.0   39.0

 

B  160.0  183.0  139.0  182.0

 

C   55.0   92.0  169.0  191.0

 

D  276.0  106.0   94.0  129.0

 

E    NaN    NaN    NaN    NaN

 

>>> de1=DataFrame(np.random.randint(0,150,size=(3,3)),index=['A','B','C'],columns=['a','b','c'])

 

>>> de1

 

     a    b    c

 

A  140    4  101

 

B  120  101  127

 

C  127   71   91

 

>>> de2

 

     a   b   c    e

 

A   35  13  90   11

 

B   58  63  59   38

 

C   18  56  49  111

 

D  142  24  29   33

 

>>> de1.add(de2)

 

       a      b      c   e

 

A  175.0   17.0  191.0 NaN

 

B  178.0  164.0  186.0 NaN

 

C  145.0  127.0  140.0 NaN

 

D    NaN    NaN    NaN NaN

 

>>> #無論是行索引還是列索引缺少了都要加NaN

 

>>> de1['a'].loc['A']=100

 

>>> de1

 

     a    b    c

 

A  100    4  101

 

B  120  101  127

 

C  127   71   91

 

>>> de1['a']

 

A    100

 

B    120

 

C    127

 

Name: a, dtype: int32

 

>>> s1=de1['a']

 

>>> s1+de1

 

    A   B   C   a   b   c

 

A NaN NaN NaN NaN NaN NaN

 

B NaN NaN NaN NaN NaN NaN

 

C NaN NaN NaN NaN NaN NaN

 

>>> #s1因為是Series索引是A,B,C,對於de1索引是a,b,c

 

>>> s2=de1.loc['A']

 

>>> s2

 

a    100

 

b      4

 

c    101

 

Name: A, dtype: int32

 

>>> s2+de1

 

     a    b    c

 

A  200    8  202

 

B  220  105  228

 

C  227   75  192

 

>>> #列索引相同所以可以相加

 

>>> s2.index

 

Index([u'a', u'b', u'c'], dtype='object')

 

>>> de1.columns

 

Index([u'a', u'b', u'c'], dtype='object')

 

>>>

 

Python提供的函數:

 

+                     add()

 

-                       sub(),或者multily()

 

*                      mul(),multiply()

 

/                        truediv(),div(),divide()

 

//                         floordiv()

 

%                        mod()

 

**                         pow()

 

>>> ss=de1['a']

 

>>> ss

 

A    100

 

B    120

 

C    127

 

Name: a, dtype: int32

 

>>> de1.add(ss)

 

    A   B   C   a   b   c

 

A NaN NaN NaN NaN NaN NaN

 

B NaN NaN NaN NaN NaN NaN

 

C NaN NaN NaN NaN NaN NaN

 

>>> de1.add(ss,axis='index')#ss的索引變成a,b,c

 

     a    b    c

 

A  200  104  201

 

B  240  221  247

 

C  254  198  218

 

 

 

>>> de1.add(ss,axis=0)

 

     a    b    c

 

A  200  104  201

 

B  240  221  247

 

C  254  198  218

 

>>> de1.add(ss,axis=1)

 

    A   B   C   a   b   c

 

A NaN NaN NaN NaN NaN NaN

 

B NaN NaN NaN NaN NaN NaN

 

C NaN NaN NaN NaN NaN NaN

 

>>> #如果axis是零,則行是索引,所有列都有效

 

>>> #以列為單位進行操作,對所有列都有效,同理axis=1相反

 

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

9:DataFrame丟失數據的處理

處理丟失數據

有兩種丟失數據 1 none 2 np.nan(NaN)

np.arange(0,10000)

#相同的計算,int運算的時間少於float,更少與object

PandasNoneNaN都被視為np.nan

df = DataFrame({'age':[20,21,23,19,22],'salary':[10000,20000,11001,10101,21000]},index=['a','b','c','d','e'],columns=['age','salary','work'])

>>> df

   age  salary work

a   20   10000  NaN

b   21   20000  NaN

c   23   11001  NaN

d   19   10101  NaN

e   22   21000  NaN

>>> df.work['a':'b']

a    NaN

b    NaN

Name: work, dtype: object

>>> df.work['a':'b']='python'

>>> df

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001     NaN

d   19   10101     NaN

e   22   21000     NaN

>>> >>> df.isnull()

     age  salary   work

a  False   False  False

b  False   False  False

c  False   False   True

d  False   False   True

e  False   False   True

>>> df.notnull()

    age  salary   work

a  True    True   True

b  True    True   True

c  True    True  False

d  True    True  False

e  True    True  False

>>> #根據獲得的數據去除數據的空數據

>>> df.dropna()#去除含有空數據的行

   age  salary    work

a   20   10000  python

b   21   20000  python

>>> #默認為行

>>> df.dropna(how='all')#去除全部為nan的行

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001     NaN

d   19   10101     NaN

e   22   21000     NaN

>>> #所有都為null的才刪除

>>> df.fillna(value='java')

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001    java

d   19   10101    java

e   22   21000    java

>>> #使空數據修改為value

#backfill,bfill,是向后填充ffill,pad是向前填充

 >>> df

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001     NaN

d   19   10101     NaN

e   22   21000     NaN

>>> df.fillna(method='backfill')#向后填充,實質是后面一行填充前面一行

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001     NaN

d   19   10101     NaN

e   22   21000     NaN

>>> df.fillna(method='ffill')#向前填充

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001  python

d   19   10101  python

e   22   21000  python

>>> df.fillna(method='ffill',inplace=True)#

>>> df

   age  salary    work

a   20   10000  python

b   21   20000  python

c   23   11001  python

d   19   10101  python

e   22   21000  python

>>> obj=pd.Series(['blue','pure','yellow'],index=[0,2,4])

>>> obj

0      blue

2      pure

4    yellow

dtype: object

>>> obj.reindex(range(6),method='bfill')

0      blue

1      pure

2      pure

3    yellow

4    yellow

5       NaN

dtype: object

>>> #這是向后填充

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

3:總結

pandas的Series和DataFrame是構成表結構的兩個重要的庫,也是學習pandas的基礎。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM