Pandas | 02 Series 系列

 

系列(Series)是可以保存任何類型的數據(整數,字符串,浮點數,Python對象等)的一維標記數組。軸標籤統稱爲索引。python

 

pandas.Series

Pandas系列可使用如下構造函數建立 -shell

 
pandas.Series( data, index, dtype, copy)
 
參數 描述
data 數據採起各類形式,如:ndarraylistconstants
index 索引值必須是惟一的和散列的,與數據的長度相同。 默認np.arange(n)若是沒有索引被傳遞。
dtype dtype用於數據類型。若是沒有,將推斷數據類型
copy 複製數據,默認爲false

 

可使用各類輸入建立一個系列,如:數組

  • 數組
  • 字典
  • 標量值或常數

 

建立一個空的系列

建立一個基本系列,是一個空系列。函數

import pandas as pd

s = pd.Series()
print(s)

輸出結果:ui

Series([], dtype: float64)
 

從ndarray建立一個系列

若是數據是ndarray,則傳遞的索引必須具備相同的長度。 若是沒有傳遞索引值,那麼默認的索引將是範圍(n),其中n是數組長度,即[0,1,2,3…. range(len(array))-1] - 1]spa

 

示例1:沒有傳遞任何索引,所以默認狀況下,它分配了從0len(data)-1的索引,即:03code

import pandas as pd
import numpy as np

data = np.array(['a','b','c','d'])
s = pd.Series(data)
print(s)

輸出結果:對象

0 a 1 b 2 c 3 d dtype: object

 示例2:傳遞了索引值。如今能夠在輸出中看到自定義的索引值blog

import pandas as pd
import numpy as np

data = np.array(['a','b','c','d'])
s = pd.Series(data,index=[100,101,102,103])
print(s)

輸出結果:排序

100 a 101 b 102 c 103 d dtype: object

 

從字典建立一個系列

  字典(dict)能夠做爲輸入傳遞,若是沒有指定索引,則按排序順序取得字典鍵以構造索引。 若是傳遞了索引,索引中與標籤對應的數據中的值將被拉出。

 示例1

import pandas as pd

data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data)
print(s)

輸出結果:

a 0.0 b 1.0 c 2.0 dtype: float64

注意 - 字典鍵用於構建索引。

 

 示例2

import pandas as pd

data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data,index=['b','c','d','a'])
print(s)

輸出結果:

b 1.0 c 2.0 d NaN a 0.0 dtype: float64 
 

注意觀察 - 索引順序保持不變,缺乏的元素使用NaN(不是數字)填充。

 

從標量建立一個系列

若是數據是標量值,則必須提供索引。將重複該值以匹配索引的長度。

import pandas as pd

s = pd.Series(5, index=[0, 1, 2, 3])
print(s)

輸出結果:

0 5 1 5 2 5 3 5 dtype: int64

從具備位置的系列中訪問數據

  系列中的數據可使用相似於訪問ndarray中的數據來訪問。

 

示例-1:檢索第一個元素。好比已經知道數組從零開始計數,第一個元素存儲在零位置等等。

import pandas as pd

s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
print(s[0])

輸出結果:

1
 

示例-2

檢索系列中的前三個元素。 若是a:被插入到其前面,則將從該索引向前的全部項目被提取。 若是使用兩個參數(使用它們之間),兩個索引之間的項目(不包括中止索引)。

import pandas as pd

s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])

#retrieve the first three element
print s[:3]

輸出結果:

a 1 b 2 c 3 dtype: int64

示例-3:檢索最後三個元素

import pandas as pd

s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])

#retrieve the last three element
print s[-3:]

輸出結果:

c 3 d 4 e 5 dtype: int64

使用標籤檢索數據(索引)

  一個系列就像一個固定大小的字典,能夠經過索引標籤獲取和設置值。

示例1:使用索引標籤值檢索單個元素。

import pandas as pd

s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])

#retrieve a single element
print s['a']

輸出結果:

1
 

示例2:使用索引標籤值列表檢索多個元素。

import pandas as pd

s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])

#retrieve multiple elements
print s[['a','c','d']]

輸出結果:

a 1 c 3 d 4 dtype: int64
 

示例3:若是不包含標籤,則會出現異常。

import pandas as pd

s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])

#retrieve multiple elements
print s['f']
 

輸出結果 :

… KeyError: 'f'
相關文章
相關標籤/搜索