pandas創建Series

如何創建Series對象

常見的創建Pandas對象的方式,都像這樣的形式:

pd.Series(data, index=index)
  • 1

其中,index是一個可選參數,data參數支持多種數據類型

例如,data可以時列表或Numpy數組,這是index默認值爲整數序列:

pd.Series([2,4,6])

Out[58]: 
0    2
1    4
2    6
dtype: int64
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

data也可以是一個標量,創建Series對象時會重複填充到每一個索引上:

pd.Series(5, index=[100, 200, 300])

Out[59]: 
100    5
200    5
300    5
dtype: int64
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

data開可以是一個字典,index默認是字典鍵:

pd.Series({2:'a', 1:'b', 3:'c'})

Out[60]: 
2    a
1    b
3    c
dtype: object
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

每一種形式都可以通過顯示指定索引篩選需要的結果:

pd.Series({2:'a', 1:'b', 3:'c'}, index=[3,2])

Out[61]: 
3    c
2    a
dtype: object
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章