pandas的數據結構

要使用pandas,須要熟悉它的兩個主要的數據結構,Series和DataFrame。python

Series

series是一種相似於覺得數組的對象,它由一組數據(各類numpy的數據類型)以及一組與之相關的數據標籤(索引)組成。僅有一組數據便可產生簡單的Series:數組

In [11]: from pandas import Series,DataFrame

In [12]: import pandas as pd

In [13]: obj=Series([4,-2,5,0])

In [14]: obj
Out[14]:
0    4
1   -2
2    5
3    0
dtype: int64

In [15]: type(obj)
Out[15]: pandas.core.series.Series

series的字符串表現形式爲:索引在左邊,值在右邊。因爲咱們沒有爲數據指定索引,因而自動建立 一個0到N-1(N爲數據的長度)的整數型索引。能夠經過Series的values和index屬性獲取其數組表現形式和索引對象:安全

In [16]: obj.values
Out[16]: array([ 4, -2,  5,  0], dtype=int64)

In [17]: obj.index
Out[17]: RangeIndex(start=0, stop=4, step=1)

一般,咱們但願所建立的Series帶有一個能夠對各個數據點進行標記的索引:數據結構

In [18]: obj2=Series([4,7,5,-3],index=['d','b','a','c'])

In [19]: obj2
Out[19]:
d    4
b    7
a    5
c   -3
dtype: int64

In [20]: obj2.index
Out[20]: Index(['d', 'b', 'a', 'c'], dtype='object')

於普通numpy相比,你能夠經過索引的方式選取Series的單個或一組值app

In [21]: obj2['a']
Out[21]: 5

In [22]: obj2['d']=6

In [23: obj2[['c','a','d']]
Out[23:
c   -3
a    5
d    6
dtype: int64

numpy數組運算都會保留索引與值之間的連接:函數

In [26]: obj2[obj2>0]
Out[26]:
d    6
b    7
a    5
dtype: int64

In [27]: obj2*2
Out[27]:
d    12
b    14
a    10
c    -6
dtype: int64

In [28]: np.exp(obj2)
Out[28]:
d     403.428793
b    1096.633158
a     148.413159
c       0.049787
dtype: float64

還能夠將Series當作一個定長的有序字典,由於它是索引值到數據值的一個映射。它能夠在許多本來須要字典參數的函數中:spa

In [29]: 'b' in obj2
Out[29]: True

In [30]: 'e' in obj2
Out[30]: False

若是數據被存放在一個Python字典中,也能夠直接經過這個字典來建立:code

In [32]: sdata={'a':1,'b':2,'c':3}

In [33]: obj3=Series(sdata)

In [34]: obj3
Out[34]:
a    1
b    2
c    3
dtype: int64

若是隻傳入一個字典,則結果series中的索引就是原字典的鍵(有序排列)對象

In [41]: states=['one','a','b']

In [42]: obj4=Series(sdata,index=states)

In [43]: obj4
Out[43]:
one    NaN
a      1.0
b      2.0
dtype: float64

例子中sdata中的states索引相匹配的那2個值會被找出來並放到相應的位置上。找不到的則用缺失值Na表示。blog

pandas中的isnull和notnull可用於檢測缺失數據:

In [44]: pd.isnull(obj4)
Out[44]:
one     True
a      False
b      False
dtype: bool

In [45]: pd.notnull(obj4)
Out[45]:
one    False
a       True
b       True
dtype: bool

series中也有相似的實例方法:

In [46]: obj4.isnull()
Out[46]:
one     True
a      False
b      False
dtype: bool

Series中最重要的一個功能是:它在算術運算中會自動對齊不一樣索引的數據。

In [47]: obj3
Out[47]:
a    1
b    2
c    3
dtype: int64

In [48]: obj4
Out[48]:
one    NaN
a      1.0
b      2.0
dtype: float64

In [49]: obj3+obj4
Out[49]:
a      2.0
b      4.0
c      NaN
one    NaN
dtype: float64

series對象自己及其索引都有一個name屬性,該屬性跟pandas其餘關鍵功能關係很是密切:

In [50]: obj4.name='pop4'

In [51]: obj4.index.name='state4'

In [52]: obj4
Out[52]:
state4
one    NaN
a      1.0
b      2.0
Name: pop4, dtype: float64

series索引能夠經過賦值的方式就地修改:

In [53]: obj
Out[53]:
0    4
1   -2
2    5
3    0
dtype: int64

In [54]: obj.index=['a','b','c','d']

In [55]: obj
Out[55]:
a    4
b   -2
c    5
d    0
dtype: int64

DataFrame

DataFrame是一個表格型數據結構。它含有一組有序的列,每列能夠是不一樣的值類型(數值、字符串、布爾值等)。DataFrame便可有行索引也能夠有列索引,它能夠被看作是由Series組成的字典(共同一個索引)跟其餘的相似的數據結構相比,DataFrame中面向行和麪向列的操做基本上是平衡的。其實,DataFrame中數據是以一個或多個二維塊存放的。

構建DataFrame最多見的方法是直接傳入一個等長列表或numpy數組組成的字典:

In [65]: data={'state':[True,True,False,True,False],'year':[2000,2001,2002,2003,2004]}

In [66]: data
Out[66]:
{'state': [True, True, False, True, False],
 'year': [2000, 2001, 2002, 2003, 2004]}

In [67]: frame=DataFrame(data)

In [68]: frame
Out[68]:
   state  year
0   True  2000
1   True  2001
2  False  2002
3   True  2003
4  False  2004

若是指定了列序列,則DataFrame的列就會按照指定順序進行排列:

In [69]: DataFrame(data,columns=['year','state'])
Out[69]:
   year  state
0  2000   True
1  2001   True
2  2002  False
3  2003   True
4  2004  False

跟series同樣,若是傳入的列在數據中找不到就會產生NA值。

經過相似字典標記的方式或屬性的方式,能夠將DataFrame的列獲取爲一個Series:

In [70]: frame['state']
Out[70]:
0     True
1     True
2    False
3     True
4    False
Name: state, dtype: bool

In [71]: frame['year']
Out[71]:
0    2000
1    2001
2    2002
3    2003
4    2004
Name: year, dtype: int64

In [72]: type(frame['year'])
Out[72]: pandas.core.series.Series

返回的series擁有DataFrame相同的索引,且其name屬性也已經被相應的設置好了 。

列能夠經過賦值的方式進行修改,如咱們增長一列‘debt’,賦上一個標量值或一組值:

In [77]: frame['debt']=16.25

In [78]: frame
Out[78]:
   state  year   debt
0   True  2000  16.25
1   True  2001  16.25
2  False  2002  16.25
3   True  2003  16.25
4  False  2004  16.25

 In [79]: frame['debt']=np.arange(5)
 In [80]: frame
 Out[80]:
    state  year  debt
 0   True  2000     0
 1   True  2001     1
 2  False  2002     2
 3   True  2003     3
 4  False  2004     4

將列表或數組賦值給某一列時,長度必需要跟DataFrame的長度相匹配。若是賦值的是一個Series,就會精匹配DataFrame的索引,全部空位都會被填上缺省值:

In [85]: frame
Out[85]:
       state  year  debt  
one     True  2000     0   
two     True  2001     1    
three  False  2002     2   
four    True  2003     3    
five   False  2004     4    

In [86]: val=Series([-1.2,-1.5,-1.7],index=['one','two','three'])

In [87]: frame['debt2']=val

In [88]: frame
Out[88]:
       state  year  debt  debt2
one     True  2000     0   -1.2
two     True  2001     1   -1.5
three  False  2002     2   -1.7
four    True  2003     3    NaN
five   False  2004     4    NaN

爲不存在的列賦值會創出一個心裂,關鍵字del用於刪除列

In [92]: del frame['state1']

In [93]: frame
Out[93]:
       state  year  debt  debt2
one     True  2000     0   -1.2
two     True  2001     1   -1.5
three  False  2002     2   -1.7
four    True  2003     3    NaN
five   False  2004     4    NaN

另外一種常見的數據形式的嵌套字典:

In [94]: pop={'year':{2001:1.5,2002:1.6,2007:2},'prices':{2001:2.5,2002:3}}

若是將它傳給DataFrame,它就會被解釋爲:外層的字典做爲鍵的關鍵列,內層的則做爲行索引:

In [95]: frame3=DataFrame(pop)

In [96]: frame3
Out[96]:
      year  prices
2001   1.5     2.5
2002   1.6     3.0
2007   2.0     NaN

能夠對結果進行轉置:

In [97]: frame3.T
Out[97]:
        2001  2002  2007
year     1.5   1.6   2.0
prices   2.5   3.0   NaN

內層的字典的鍵會被合併、排序以造成最終的索引。若是顯式指定了索引:

In [109]: frame3.index=[2001,2002,2003]

In [111]: frame3
Out[111]:
      year  prices
2001   1.5     2.5
2002   1.6     3.0
2003   2.0     NaN

能夠輸入給DataFrame構造器的數據:

1.二維ndarry

2.由數組、列表或元祖組成的字典

3.numpy結構化

4.Series組成的字典

5.由字典組成的字典

6.字典或series的列表

7.由列表或元祖組成的列表

8.另外一個DataFrame

9.numpy的MaskedArray

若是設置了DataFrame的index和columns的name屬性,則這些信息也會顯示出來

In [113]: frame3.index.name='year';frame3.columns.name='state'

In [114]: frame3
Out[114]:
state  year  prices
year
2001    1.5     2.5
2002    1.6     3.0
2003    2.0     NaN

索引對象

 pandas的索引對象負責管理軸標籤和其餘元數據(如軸名稱)構建series或DataFrame時,所用到的任何數組或其餘序列的標籤都會被轉換成一個index:

In [116]: obj=Series(range(3),index=['b','a','c'])

In [117]: index=obj.index

In [118]: index
Out[118]: Index(['b', 'a', 'c'], dtype='object')

In [121]: index[1:]
Out[121]: Index(['a', 'c'], dtype='object')

Index對象是不可修改的(immutable),所以用戶不可對其進行修改

In [122]: index[1]='f'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-122-c2c86828e313> in <module>()
----> 1 index[1]='f'

d:\python\python36\lib\site-packages\pandas\core\indexes\base.py in __setitem__(self, key, value)
   2048
   2049     def __setitem__(self, key, value):
-> 2050         raise TypeError("Index does not support mutable operations")
   2051
   2052     def __getitem__(self, key):

TypeError: Index does not support mutable operations

不可修改屬性很是重要,由於這樣才能使Index對象在多個數據結構之間數據安全共享

In [123]: index=pd.Index(np.arange(3))

In [127]: obj2=Series([-1.5,2.6,0],index=index)

In [129]: obj2
Out[129]:
0   -1.5
1    2.6
2    0.0
dtype: float64

In [130]: obj2.index is index
Out[130]: True

pandas中主要的index對象:

index : 最泛化的index對象,將軸標籤表示爲一個由Python對象組成的numpy數組

int64index:針對整數的特殊index

Multiindex :層次化索引對象,表示單個軸上的多層索引。能夠當作由元組組成的數組

DatatimeIndex :存儲納秒級時間戳

Periodindex:針對Period數據(時間間隔)的特殊index

除了長得像數組,index的功能相似一個固定大小的集合:

In [131]: frame3
Out[131]:
state  year  prices
year
2001    1.5     2.5
2002    1.6     3.0
2003    2.0     NaN

In [132]: 'year' in frame3.columns
Out[132]: True

In [133]: '2001'  in frame3.index
Out[133]: False

In [134]: 2001  in frame3.index
Out[134]: True

 

index的方法和屬性:

append:鏈接另外一個index對象,產生一個新的index

diff:計算差集,並獲得一個新的index

intersection:計算交集

union:計算並集

isin:計算一個指示各值是否都包含在參數集合中的布爾型數組

delete:刪除索引i處的元素,並獲得一個新的index

drop:刪除傳入的值,並獲得一個新的index

insert:將元素插入到索引i處,並獲得一個新的index

is_monotonic:當各元素大於等於前一個元素時,返回True

is_unique:當index沒有重複值時,返回True

unique:計算index中惟一值得數組

相關文章
相關標籤/搜索