pandas 數據結構之Series的使用方法

這篇文章主要介紹了pandas 數據結構之Series的使用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

1. Series

Series 是一個類數組的數據結構,同時帶有標籤(lable)或者說索引(index)。

1.1 下邊生成一個最簡單的Series對象,因爲沒有給Series指定索引,所以此時會使用默認索引(從0到N-1)。

# 引入Series和DataFrame
In [16]: from pandas import Series,DataFrame
In [17]: import pandas as pd

In [18]: ser1 = Series([1,2,3,4])

In [19]: ser1
Out[19]: 
0  1
1  2
2  3
3  4
dtype: int64

1.2 當要生成一個指定索引的Series 時候,可以這樣:  

# 給index指定一個list
In [23]: ser2 = Series(range(4),index = ["a","b","c","d"])

In [24]: ser2
Out[24]: 
a  0
b  1
c  2
d  3
dtype: int64

1.3 也可以通過字典來創建Series對象

In [45]: sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}

In [46]: ser3 = Series(sdata)
# 可以發現,用字典創建的Series是按index有序的
In [47]: ser3
Out[47]: 
Ohio   35000
Oregon  16000
Texas   71000
Utah    5000
dtype: int64

在用字典生成Series的時候,也可以指定索引,當索引中值對應的字典中的值不存在的時候,則此索引的值標記爲Missing,NA,並且可以通過函數(pandas.isnull,pandas.notnull)來確定哪些索引對應的值是沒有的。 

In [48]: states = ['California', 'Ohio', 'Oregon', 'Texas']

In [49]: ser3 = Series(sdata,index = states)

In [50]: ser3
Out[50]: 
California    NaN
Ohio     35000.0
Oregon    16000.0
Texas     71000.0
dtype: float64
# 判斷哪些值爲空
In [51]: pd.isnull(ser3)
Out[51]: 
California   True
Ohio     False
Oregon    False
Texas     False
dtype: bool

In [52]: pd.notnull(ser3)
Out[52]: 
California  False
Ohio      True
Oregon     True
Texas     True
dtype: bool

1.4 訪問Series中的元素和索引:

# 訪問索引爲"a"的元素
In [25]: ser2["a"]
Out[25]: 0
# 訪問索引爲"a","c"的元素
In [26]: ser2[["a","c"]]
Out[26]: 
a  0
c  2
dtype: int64
# 獲取所有的值
In [27]: ser2.values
Out[27]: array([0, 1, 2, 3])
# 獲取所有的索引
In [28]: ser2.index
Out[28]: Index([u'a', u'b', u'c', u'd'], dtype='object')

1.5 簡單運算

在pandas的Series中,會保留NumPy的數組操作(用布爾數組過濾數據,標量乘法,以及使用數學函數),並同時保持引用的使用

In [34]: ser2[ser2 > 2]
Out[34]: 
a  64
d   3
dtype: int64

In [35]: ser2 * 2
Out[35]: 
a  128
b   2
c   4
d   6
dtype: int64

In [36]: np.exp(ser2)
Out[36]: 
a  6.235149e+27
b  2.718282e+00
c  7.389056e+00
d  2.008554e+01
dtype: float64

1.6 Series的自動對齊

Series的一個重要功能就是自動對齊(不明覺厲),看看例子就明白了。 差不多就是不同Series對象運算的時候根據其索引進行匹配計算。

# ser3 的內容
In [60]: ser3
Out[60]: 
Ohio   35000
Oregon  16000
Texas   71000
Utah    5000
dtype: int64
# ser4 的內容
In [61]: ser4
Out[61]: 
California    NaN
Ohio     35000.0
Oregon    16000.0
Texas     71000.0
dtype: float64
# 相同索引值的元素相加
In [62]: ser3 + ser4
Out[62]: 
California     NaN
Ohio      70000.0
Oregon     32000.0
Texas     142000.0
Utah        NaN
dtype: float64

1.7 命名

Series對象本身,以及索引都有一個 name 屬性

In [64]: ser4.index.name = "state"

In [65]: ser4.name = "population"

In [66]: ser4
Out[66]: 
state
California    NaN
Ohio     35000.0
Oregon    16000.0
Texas     71000.0
Name: population, dtype: float64

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章