# `pandas`數據結構之`Series`
> `Series`是一種類似于一維數組的對象,由一組數據(各種`NumPy`數據類型)以及一組與之相關的數據標簽(即索引)組成。
* * *
~~~
from pandas import Series, DataFrame
import pandas as pd
obj = Series([4, 7, -5, 3])
print(obj)
//
0 4
1 7
2 -5
3 3
dtype: int64
~~~
從上面代碼可以看出,`Series`的字符串表現形式為:索引在左邊,值在右邊。在沒有為數據指定索引的前提下,會自動創建一個從0到N-1的整數型索引。可以通過`Series`的`values`和`index`屬性獲取其數組表示形式和索引對象。
~~~
from pandas import Series, DataFrame
import pandas as pd
obj = Series([4, 7, -5, 3])
print(obj.index)
//RangeIndex(start=0, stop=4, step=1)
print(obj.values)
//[ 4 7 -5 3]
~~~
* * *
通常,我們希望所創建的`Series`帶有一個可以對各個數據點進行標記的索引:
~~~
from pandas import Series, DataFrame
import pandas as pd
obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
print(obj2)
//
d 4
b 7
a -5
c 3
dtype: int64
~~~
* * *
與普通`NumPy`數組相比,`Seria`可以通過索引的方式選取一個或一組值:
~~~
from pandas import Series, DataFrame
import pandas as pd
obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
print(obj2['a'])
//-5
obj2['d'] = 6
print(obj2[['c', 'a', 'd']])
//
c 3
a -5
d 6
dtype: int64
~~~
* * *
`NumPy`數組運算(如根據布爾型數組進行過濾,標量乘法,應用數學函數等)都會保留索引和值之間的鏈接:
~~~
from pandas import Series, DataFrame
import pandas as pd
obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
obj2['d'] = 6
print(obj2[obj2 > 0])
//
d 6
b 7
c 3
dtype: int64
print(obj2*2)
//
d 12
b 14
a -10
c 6
dtype: int64
~~~
* * *
還可以將`Series`看成是一個定長的有序字典,因為它是索引值到數據值的映射。它可以用在原本需要字典參數的函數中:
~~~
from pandas import Series, DataFrame
import pandas as pd
obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
obj2['d'] = 6
print('b' in obj2)
//True
print('e' in obj2)
//False
~~~
* * *
如果數據被存放在一個`Python`字典中,也可以直接通過這個字典來創建`Series`
~~~
from pandas import Series, DataFrame
import pandas as pd
sData = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
obj3 = Series(sData)
print(obj3)
//
Ohio 35000
Oregon 16000
Texas 71000
Utah 5000
dtype: int64
~~~