Pandas資料分析

  1. Pandas 的名稱是源自於 “panel data” 一詞,是計量經濟學(econometrics) 的資料集名詞
  2. Pandas 架構於 NumPy 之上的新套件,提供高效率的 DataFrame實作
  3. DataFrames 是基礎的多維陣列,加上列與欄的標籤,一般存放異質性的資料,也可能是空值(missing data)
  4. Pandas,尤其是 Series 與 DataFrame 物件,建構在 NumPy 陣列之上,提供強大且有效率的資料整理 “data munging” 功能,這也是資料科學家最耗費時間的地方
  5. Panel ( 三維度 ) DataFrame 的資料結構,於 0.25.0 版移除

建立Series物件

Pandas Series 可視為有標籤索引的一維陣列資料

data = pd.Series([0.25, 0.5, 0.75, 1.0])
data
# 0    0.25
# 1    0.50
# 2    0.75
# 3    1.00
# dtype: float64

Series as generalized NumPy array

data = pd.Series([0.25, 0.5, 0.75, 1.0],
                 index=['a', 'b', 'c', 'd'])
data
# a    0.25
# b    0.50
# c    0.75
# d    1.00
# dtype: float64
data = pd.Series([0.25, 0.5, 0.75, 1.0])
data
# 0    0.25
# 1    0.50
# 2    0.75
# 3    1.00
# dtype: float64

data.values
# array([0.25, 0.5 , 0.75, 1.  ])

data.index
# RangeIndex(start=0, stop=4, step=1)

data.shape
# (4,)

data.ndim
# 1

# Get data type 
data.dtypes
# dtype('float64')
# index can be duplicated
obj = pd.Series (range(5), index=['a', 'a', 'b', 'b', 'c'])

# get all objects with index 'a'
obj['a']
# a    0
# a    1
# dtype: int64

# Check if index is unique
obj.index.is_unique
# False

The Pandas Index Object

ind = pd.Index([2, 3, 5, 7, 11])
ind
# Int64Index([2, 3, 5, 7, 11], dtype='int64')

ind[1]
# 3

ind[::2]
# Int64Index([2, 5, 11], dtype='int64')

print(ind.size, ind.shape, ind.ndim, ind.dtype)
# 5 (5,) 1 int64

Index as ordered set

indA = pd.Index([1, 3, 5, 7, 9])
indB = pd.Index([2, 3, 5, 7, 11])

indA & indB  # intersection
# Int64Index([3, 5, 7], dtype='int64')

indA | indB  # union
# Int64Index([1, 2, 3, 5, 7, 9, 11], dtype='int64')

indA ^ indB  # symmetric difference
# Int64Index([1, 2, 9, 11], dtype='int64')

indA.intersection(indB)
# Int64Index([3, 5, 7], dtype='int64')



資料型態是單一型態(Homogenous)
Pandas Series 比起 NumPy 的一維陣列,處理起來更加方便與彈性

Series 語法

pd.Series(data, index=index)

index參數是選擇性的

data可用多種方式表達,data可以是列表或Numpy數組,甚至可以是標量,字典,index默認值為整數數列。