學習彙總:點這裏
系列(Series)是能夠保存任何類型的數據(整數,字符串,浮點數,Python對象等)的一維標記數組。軸標籤統稱爲索引。
pandas.Series
Pandas系列可以使用以下構造函數創建 :
pandas.Series( data, index, dtype, copy)。
Python構造函數的參數如下:
編號 | 參數 | 描述 |
---|---|---|
1 | data | 數據採取各種形式,如:ndarray,list,constants |
2 | index | 索引值必須是唯一的和散列的,與數據的長度相同。 默認np.arange(n)如果沒有索引被傳遞。 |
3 | dtype | dtype用於數據類型。如果沒有,將推斷數據類型 |
4 | copy | 複製數據,默認爲false。 |
創建Series
可以使用各種輸入創建一個系列,如 :
- 數組
- 字典
- 標量值或常數
1.創建一個空的系列
>>>import pandas as pd
>>>s = pd.Series()
>>>s
Series([], dtype: float64)
>>>s.values
array([], dtype=float64)
>>>s.index
Index([], dtype='object')
2.從ndarray創建一個系列
如果數據是ndarray,則傳遞的索引必須具有相同的長度。 如果沒有傳遞索引值,那麼默認的索引將是範圍(n),其中n是數組長度,即[0,1,2,3…. range(len(array))-1] - 1]。
#這裏沒有傳遞任何索引,因此默認情況下,它分配了從0到len(data)-1的索引,即:0到3。
>>>import pandas as pd
>>>import numpy as np
>>>data = np.array(['a','b','c','d'])
>>>s = pd.Series(data)
>>>s
0 a
1 b
2 c
3 d
dtype: object
3.從字典創建一個系列
字典(dict)可以作爲輸入傳遞,如果沒有指定索引,則按排序順序取得字典鍵以構造索引。 如果傳遞了索引,索引中與標籤對應的數據中的值將被拉出。
>>>import pandas as pd
>>>import numpy as np
>>>data = {'a' : 0., 'b' : 1., 'c' : 2.}
>>>s = pd.Series(data,index=['b','c','d','a'])
>>>s
b 1.0
c 2.0
d NaN
a 0.0
dtype: float64
注意:索引順序保持不變,缺少的元素使用NaN(不是數字)填充。
4.從標量創建一個系列
如果數據是標量值,則必須提供索引。將重複該值以匹配索引的長度。
>>>import pandas as pd
>>>import numpy as np
>>>s = pd.Series(5, index=[0, 1, 2, 3])
>>>s
0 5
1 5
2 5
3 5
dtype: int64
訪問數據
1.系列中的數據可以使用類似於訪問ndarray中的數據來訪問。
>>>import pandas as pd
>>>s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
>>>s[0]
1
2.檢索系列中的前三個元素。 如果a:被插入到其前面,則將從該索引向前的所有項目被提取。 如果使用兩個參數(使用它們之間),兩個索引之間的項目(不包括停止索引)。
>>>import pandas as pd
>>>s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
>>>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'])
>>>s['a']
1
4.使用索引標籤值列表檢索多個元素。
>>>import pandas as pd
>>>s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
>>>s[['a','c','d']]
a 1
c 3
d 4
dtype: int64