第三部分數據分析工具Pandas
Pandas的名稱來自於面板數據(panel data)和Python數據分析(data analysis)。
Pandas是一個強大的分析結構化數據的工具集,基於NumPy構建,提供了 高級數據結構 和 數據操作工具,它是使Python成爲強大而高效的數據分析環境的重要因素之一。
- 一個強大的分析和操作大型結構化數據集所需的工具集
- 基礎是NumPy,提供了高性能矩陣的運算
- 提供了大量能夠快速便捷地處理數據的函數和方法
- 應用於數據挖掘,數據分析
- 提供數據清洗功能
安裝
pip install pandas
一、Pandas的數據結構
import pandas as pd
Pandas有兩個最主要也是最重要的數據結構: Series 和 DataFrame
1、Series
Series是一種類似於一維數組的 對象,由一組數據(各種NumPy數據類型)以及一組與之對應的索引(數據標籤)組成。
- 類似一維數組的對象
- 由數據和索引組成
- 索引(index)在左,數據(values)在右
- 索引是自動創建的
1. 通過list構建Series
ser_obj = pd.Series(range(10))
示例代碼:
# 通過list構建Series
ser_obj = pd.Series(range(10, 20))
print(ser_obj.head(3))
print(ser_obj)
print(type(ser_obj))
運行結果:
0 10
1 11
2 12
dtype: int64
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
dtype: int64
<class 'pandas.core.series.Series'>
2. 獲取數據和索引
ser_obj.index 和 ser_obj.values
示例代碼:
# 獲取數據
print(ser_obj.values)
# 獲取索引
print(ser_obj.index)
運行結果:
[10 11 12 13 14 15 16 17 18 19]
RangeIndex(start=0, stop=10, step=1)
3. 通過索引獲取數據
ser_obj[idx]
示例代碼:
#通過索引獲取數據
print(ser_obj[0])
print(ser_obj[8])
運行結果:
10
18
4. 索引與數據的對應關係不被運算結果影響
示例代碼:
# 索引與數據的對應關係不被運算結果影響
print(ser_obj * 2)
print(ser_obj > 15)
運行結果:
0 20
1 22
2 24
3 26
4 28
5 30
6 32
7 34
8 36
9 38
dtype: int64
0 False
1 False
2 False
3 False
4 False
5 False
6 True
7 True
8 True
9 True
dtype: bool
5. 通過dict構建Series
示例代碼:
# 通過dict構建Series
year_data = {2001: 17.8, 2002: 20.1, 2003: 16.5}
ser_obj2 = pd.Series(year_data)
print(ser_obj2.head())
print(ser_obj2.index)
運行結果:
2001 17.8
2002 20.1
2003 16.5
dtype: float64
Int64Index([2001, 2002, 2003], dtype='int64')
name屬性
對象名:ser_obj.name
對象索引名:ser_obj.index.name
示例代碼:
# name屬性
ser_obj2.name = 'temp'
ser_obj2.index.name = 'year'
print(ser_obj2.head())
運行結果:
year
2001 17.8
2002 20.1
2003 16.5
Name: temp, dtype: float64
2、DataFrame
DataFrame是一個表格型的數據結構,它含有一組有序的列,每列可以是不同類型的值。DataFrame既有行索引也有列索引,它可以被看做是由Series組成的字典(共用同一個索引),數據是以二維結構存放的。
- 類似多維數組/表格數據 (如,excel, R中的data.frame)
- 每列數據可以是不同的類型
- 索引包括列索引和行索引
1. 通過ndarray構建DataFrame
示例代碼:
import numpy as np
# 通過ndarray構建DataFrame
array = np.random.randn(5,4)
print(array)
df_obj = pd.DataFrame(array)
print(df_obj.head())
運行結果:
[[ 0.83500594 -1.49290138 -0.53120106 -0.11313932]
[ 0.64629762 -0.36779941 0.08011084 0.60080495]
[-1.23458522 0.33409674 -0.58778195 -0.73610573]
[-1.47651414 0.99400187 0.21001995 -0.90515656]
[ 0.56669419 1.38238348 -0.49099007 1.94484598]]
0 1 2 3
0 0.835006 -1.492901 -0.531201 -0.113139
1 0.646298 -0.367799 0.080111 0.600805
2 -1.234585 0.334097 -0.587782 -0.736106
3 -1.476514 0.994002 0.210020 -0.905157
4 0.566694 1.382383 -0.490990 1.944846
2. 通過dict構建DataFrame
示例代碼:
# 通過dict構建DataFrame
dict_data = {'A': 1,
'B': pd.Timestamp('20170426'),
'C': pd.Series(1, index=list(range(4)),dtype='float32'),
'D': np.array([3] * 4,dtype='int32'),
'E': ["Python","Java","C++","C"],
'F': 'ITCast' }
#print dict_data
df_obj2 = pd.DataFrame(dict_data)
print(df_obj2)
運行結果:
A B C D E F
0 1 2017-04-26 1.0 3 Python ITCast
1 1 2017-04-26 1.0 3 Java ITCast
2 1 2017-04-26 1.0 3 C++ ITCast
3 1 2017-04-26 1.0 3 C ITCast
3. 通過列索引獲取列數據(Series類型)
df_obj[col_idx] 或 df_obj.col_idx
示例代碼:
# 通過列索引獲取列數據
print(df_obj2['A'])
print(type(df_obj2['A']))
print(df_obj2.A)
運行結果:
0 1.0
1 1.0
2 1.0
3 1.0
Name: A, dtype: float64
<class 'pandas.core.series.Series'>
0 1.0
1 1.0
2 1.0
3 1.0
Name: A, dtype: float64
4. 增加列數據
df_obj[new_col_idx] = data
類似Python的 dict添加key-value
示例代碼:
# 增加列
df_obj2['G'] = df_obj2['D'] + 4
print(df_obj2.head())
運行結果:
A B C D E F G
0 1.0 2017-01-02 1.0 3 Python ITCast 7
1 1.0 2017-01-02 1.0 3 Java ITCast 7
2 1.0 2017-01-02 1.0 3 C++ ITCast 7
3 1.0 2017-01-02 1.0 3 C ITCast 7
5. 刪除列
del df_obj[col_idx]
示例代碼:
# 刪除列
del(df_obj2['G'] )
print(df_obj2.head())
運行結果:
A B C D E F
0 1.0 2017-01-02 1.0 3 Python ITCast
1 1.0 2017-01-02 1.0 3 Java ITCast
2 1.0 2017-01-02 1.0 3 C++ ITCast
3 1.0 2017-01-02 1.0 3 C ITCast
二、Pandas的索引操作
1、索引對象Index
1. Series和DataFrame中的索引都是Index對象
示例代碼:
print(type(ser_obj.index))
print(type(df_obj2.index))
print(df_obj2.index)
運行結果:
<class 'pandas.indexes.range.RangeIndex'>
<class 'pandas.indexes.numeric.Int64Index'>
Int64Index([0, 1, 2, 3], dtype='int64')
2. 索引對象不可變,保證了數據的安全
示例代碼:
# 索引對象不可變
df_obj2.index[0] = 2
運行結果:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-23-7f40a356d7d1> in <module>()
1 # 索引對象不可變
----> 2 df_obj2.index[0] = 2
/Users/Power/anaconda/lib/python3.6/site-packages/pandas/indexes/base.py in __setitem__(self, key, value)
1402
1403 def __setitem__(self, key, value):
-> 1404 raise TypeError("Index does not support mutable operations")
1405
1406 def __getitem__(self, key):
TypeError: Index does not support mutable operations
常見的Index種類
- Index,索引
- Int64Index,整數索引
- MultiIndex,層級索引
- DatetimeIndex,時間戳類型
2、Series索引
1. index 指定行索引名
示例代碼:
ser_obj = pd.Series(range(5), index = ['a', 'b', 'c', 'd', 'e'])
print(ser_obj.head())
運行結果:
a 0
b 1
c 2
d 3
e 4
dtype: int64
2. 行索引
ser_obj[‘label’], ser_obj[pos]
示例代碼:
# 行索引
print(ser_obj['b'])
print(ser_obj[2])
運行結果:
1
2
3. 切片索引
ser_obj[2:4], ser_obj[‘label1’: ’label3’]
注意,按索引名切片操作時,是包含終止索引的。
示例代碼:
# 切片索引
print(ser_obj[1:3])
print(ser_obj['b':'d'])
運行結果:
b 1
c 2
dtype: int64
b 1
c 2
d 3
dtype: int64
4. 不連續索引
ser_obj[[‘label1’, ’label2’, ‘label3’]]
示例代碼:
# 不連續索引
print(ser_obj[[0, 2, 4]])
print(ser_obj[['a', 'e']])
運行結果:
a 0
c 2
e 4
dtype: int64
a 0
e 4
dtype: int64
5. 布爾索引
示例代碼:
# 布爾索引
ser_bool = ser_obj > 2
print(ser_bool)
print(ser_obj[ser_bool])
print(ser_obj[ser_obj > 2])
運行結果:
a False
b False
c False
d True
e True
dtype: bool
d 3
e 4
dtype: int64
d 3
e 4
dtype: int64
3、DataFrame索引
1. columns 指定列索引名
示例代碼:
import numpy as np
df_obj = pd.DataFrame(np.random.randn(5,4), columns = ['a', 'b', 'c', 'd'])
print(df_obj.head())
運行結果:
a b c d
0 -0.241678 0.621589 0.843546 -0.383105
1 -0.526918 -0.485325 1.124420 -0.653144
2 -1.074163 0.939324 -0.309822 -0.209149
3 -0.716816 1.844654 -2.123637 -1.323484
4 0.368212 -0.910324 0.064703 0.486016
2. 列索引
df_obj[[‘label’]]
示例代碼:
# 列索引
print(df_obj['a']) # 返回Series類型
print(df_obj[[0]]) # 返回DataFrame類型
print(type(df_obj[[0]])) # 返回DataFrame類型
運行結果:
0 -0.241678
1 -0.526918
2 -1.074163
3 -0.716816
4 0.368212
Name: a, dtype: float64
<class 'pandas.core.frame.DataFrame'>
3. 不連續索引
df_obj[[‘label1’, ‘label2’]]
示例代碼:
# 不連續索引
print(df_obj[['a','c']])
print(df_obj[[1, 3]])#ERROR!
運行結果:
a c
0 -0.241678 0.843546
1 -0.526918 1.124420
2 -1.074163 -0.309822
3 -0.716816 -2.123637
4 0.368212 0.064703
b d
0 0.621589 -0.383105
1 -0.485325 -0.653144
2 0.939324 -0.209149
3 1.844654 -1.323484
4 -0.910324 0.486016
高級索引:標籤、位置和混合
Pandas的高級索引有3種
1. loc 標籤索引
DataFrame 不能直接切片,可以通過loc來做切片
loc是基於標籤名的索引,也就是我們自定義的索引名
示例代碼:
# 標籤索引 loc
# Series
print(ser_obj['b':'d'])
print(ser_obj.loc['b':'d'])
# DataFrame
print(df_obj['a'])
# 第一個參數索引行,第二個參數是列
print(df_obj.loc[0:2, 'a'])
運行結果:
b 1
c 2
d 3
dtype: int64
b 1
c 2
d 3
dtype: int64
0 -0.241678
1 -0.526918
2 -1.074163
3 -0.716816
4 0.368212
Name: a, dtype: float64
0 -0.241678
1 -0.526918
2 -1.074163
Name: a, dtype: float64
2. iloc 位置索引
作用和loc一樣,不過是基於索引編號來索引
示例代碼:
# 整型位置索引 iloc
# Series
print(ser_obj[1:3])
print(ser_obj.iloc[1:3])
# DataFrame
print(df_obj.iloc[0:2, 0]) # 注意和df_obj.loc[0:2, 'a']的區別
運行結果:
b 1
c 2
dtype: int64
b 1
c 2
dtype: int64
0 -0.241678
1 -0.526918
Name: a, dtype: float64
3. ix 標籤與位置混合索引
ix是以上二者的綜合,既可以使用索引編號,又可以使用自定義索引,要視情況不同來使用,
如果索引既有數字又有英文,那麼這種方式是不建議使用的,容易導致定位的混亂。
示例代碼:
# 混合索引 ix
# Series
print(ser_obj.ix[1:3])
print(ser_obj.ix['b':'c'])
# DataFrame
print(df_obj.loc[0:2, 'a'])
print(df_obj.ix[0:2, 0])
print(df_obj.ix[0:2, 0:2])
運行結果:
b 1
c 2
dtype: int64
b 1
c 2
dtype: int64
0 -0.241678
1 -0.526918
2 -1.074163
Name: a, dtype: float64
注意
DataFrame索引操作,可將其看作ndarray的索引操作
標籤的切片索引是包含末尾位置的
三、Pandas的對齊運算
是數據清洗的重要過程,可以按索引對齊進行運算,如果沒對齊的位置則補NaN,最後也可以填充NaN
Series的對齊運算
1. Series 按行、索引對齊
示例代碼:
print('s1: ' )
print(s1)
print('')
print('s2: ')
print(s2)
運行結果:
s1:
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
dtype: int64
s2:
0 20
1 21
2 22
3 23
4 24
dtype: int64
2. Series的對齊運算
示例代碼:
# Series 對齊運算
s1 + s2
運行結果:
0 30.0
1 32.0
2 34.0
3 36.0
4 38.0
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
dtype: float64
DataFrame的對齊運算
1. DataFrame按行、列索引對齊
示例代碼:
df1 = pd.DataFrame(np.ones((2,2)), columns = ['a', 'b'])
df2 = pd.DataFrame(np.ones((3,3)), columns = ['a', 'b', 'c'])
print('df1: ')
print(df1)
print('')
print('df2: ')
print(df2)
運行結果:
df1:
a b
0 1.0 1.0
1 1.0 1.0
df2:
a b c
0 1.0 1.0 1.0
1 1.0 1.0 1.0
2 1.0 1.0 1.0
2. DataFrame的對齊運算
示例代碼:
# DataFrame對齊操作
df1 + df2
運行結果:
a b c
0 2.0 2.0 NaN
1 2.0 2.0 NaN
2 NaN NaN NaN
填充未對齊的數據進行運算
1. fill_value
使用
add
,sub
,div
,mul
的同時,通過
fill_value
指定填充值,未對齊的數據將和填充值做運算
示例代碼:
print(s1)
print(s2)
s1.add(s2, fill_value = -1)
print(df1)
print(df2)
df1.sub(df2, fill_value = 2.)
運行結果:
# print(s1)
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
dtype: int64
# print(s2)
0 20
1 21
2 22
3 23
4 24
dtype: int64
# s1.add(s2, fill_value = -1)
0 30.0
1 32.0
2 34.0
3 36.0
4 38.0
5 14.0
6 15.0
7 16.0
8 17.0
9 18.0
dtype: float64
# print(df1)
a b
0 1.0 1.0
1 1.0 1.0
# print(df2)
a b c
0 1.0 1.0 1.0
1 1.0 1.0 1.0
2 1.0 1.0 1.0
# df1.sub(df2, fill_value = 2.)
a b c
0 0.0 0.0 1.0
1 0.0 0.0 1.0
2 1.0 1.0 1.0
四、Pandas的函數應用
apply 和 applymap
1. 可直接使用NumPy的函數
示例代碼:
# Numpy ufunc 函數
df = pd.DataFrame(np.random.randn(5,4) - 1)
print(df)
print(np.abs(df))
運行結果:
0 1 2 3
0 -0.062413 0.844813 -1.853721 -1.980717
1 -0.539628 -1.975173 -0.856597 -2.612406
2 -1.277081 -1.088457 -0.152189 0.530325
3 -1.356578 -1.996441 0.368822 -2.211478
4 -0.562777 0.518648 -2.007223 0.059411
0 1 2 3
0 0.062413 0.844813 1.853721 1.980717
1 0.539628 1.975173 0.856597 2.612406
2 1.277081 1.088457 0.152189 0.530325
3 1.356578 1.996441 0.368822 2.211478
4 0.562777 0.518648 2.007223 0.059411
2. 通過apply將函數應用到列或行上
示例代碼:
# 使用apply應用行或列數據
#f = lambda x : x.max()
print(df.apply(lambda x : x.max()))
運行結果:
0 -0.062413
1 0.844813
2 0.368822
3 0.530325
dtype: float64
注意指定軸的方向,默認axis=0,方向是列
示例代碼:
# 指定軸方向,axis=1,方向是行
print(df.apply(lambda x : x.max(), axis=1))
運行結果:
0 0.844813
1 -0.539628
2 0.530325
3 0.368822
4 0.518648
dtype: float64
3. 通過applymap將函數應用到每個數據上(apply+自定義函數)
示例代碼:
# 使用applymap應用到每個數據
f2 = lambda x : '%.2f' % x
print(df.applymap(f2))
print("apply+自定義函數:")
def pn(x):
return x*10;
print(df.apply(pn))
運行結果:
0 1 2 3
0 -0.06 0.84 -1.85 -1.98
1 -0.54 -1.98 -0.86 -2.61
2 -1.28 -1.09 -0.15 0.53
3 -1.36 -2.00 0.37 -2.21
4 -0.56 0.52 -2.01 0.06
排序
1. 索引排序
sort_index()
排序默認使用升序排序,ascending=False 爲降序排序
示例代碼:
# Series
s4 = pd.Series(range(10, 15), index = np.random.randint(5, size=5))
print(s4)
# 索引排序
s4.sort_index() # 0 0 1 3 3
運行結果:
0 10
3 11
1 12
3 13
0 14
dtype: int64
0 10
0 14
1 12
3 11
3 13
dtype: int64
對DataFrame操作時注意軸方向
示例代碼:
# DataFrame
df4 = pd.DataFrame(np.random.randn(3, 5),
index=np.random.randint(3, size=3),
columns=np.random.randint(5, size=5))
print(df4)
# axis=1(列排序)ascending=Ture(升序)
df4_isort = df4.sort_index(axis=1, ascending=Ture)
print(df4_isort) # 4 2 1 1 0
運行結果:
1 4 0 1 2
2 -0.416686 -0.161256 0.088802 -0.004294 1.164138
1 -0.671914 0.531256 0.303222 -0.509493 -0.342573
1 1.988321 -0.466987 2.787891 -1.105912 0.889082
4 2 1 1 0
2 -0.161256 1.164138 -0.416686 -0.004294 0.088802
1 0.531256 -0.342573 -0.671914 -0.509493 0.303222
1 -0.466987 0.889082 1.988321 -1.105912 2.787891
2. 按值排序
sort_values(by=‘column name’)
根據某個唯一的列名進行排序,如果有其他相同列名則報錯。
示例代碼:
# 按值排序
df4_vsort = df4.sort_values(by=0, ascending=False)
print(df4_vsort)
運行結果:
1 4 0 1 2
1 1.988321 -0.466987 2.787891 -1.105912 0.889082
1 -0.671914 0.531256 0.303222 -0.509493 -0.342573
2 -0.416686 -0.161256 0.088802 -0.004294 1.164138
五、處理缺失數據
示例代碼:
df_data = pd.DataFrame([np.random.randn(3), [1., 2., np.nan],
[np.nan, 4., np.nan], [1., 2., 3.]])
print(df_data.head())
運行結果:
0 1 2
0 -0.281885 -0.786572 0.487126
1 1.000000 2.000000 NaN
2 NaN 4.000000 NaN
3 1.000000 2.000000 3.000000
1. 判斷是否存在缺失值:isnull()
示例代碼:
# isnull
print(df_data.isnull())
運行結果:
0 1 2
0 False False False
1 False False True
2 True False True
3 False False False
2. 丟棄缺失數據:dropna()
根據axis軸方向,丟棄包含NaN的行或列。 示例代碼:
# dropna
print(df_data.dropna())
print(df_data.dropna(axis=1))
運行結果:
0 1 2
0 -0.281885 -0.786572 0.487126
3 1.000000 2.000000 3.000000
1
0 -0.786572
1 2.000000
2 4.000000
3 2.000000
3. 填充缺失數據:fillna()
示例代碼:
# fillna
print(df_data.fillna(-100.))
運行結果:
0 1 2
0 -0.281885 -0.786572 0.487126
1 1.000000 2.000000 -100.000000
2 -100.000000 4.000000 -100.000000
3 1.000000 2.000000 3.000000
六、層級索引(hierarchical indexing)
下面創建一個Series, 在輸入索引Index時,輸入了由兩個子list組成的list,第一個子list是外層索引,第二個list是內層索引。
示例代碼:
import pandas as pd
import numpy as np
ser_obj = pd.Series(np.random.randn(12),index=[
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'],
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]
])
print(ser_obj)
運行結果:
a 0 0.099174
1 -0.310414
2 -0.558047
b 0 1.742445
1 1.152924
2 -0.725332
c 0 -0.150638
1 0.251660
2 0.063387
d 0 1.080605
1 0.567547
2 -0.154148
dtype: float64
MultiIndex索引對象
- 打印這個Series的索引類型,顯示是MultiIndex
- 直接將索引打印出來,可以看到有lavels,和labels兩個信息。lavels表示兩個層級中分別有那些標籤,labels是每個位置分別是什麼標籤。
示例代碼:
print(type(ser_obj.index))
print(ser_obj.index)
運行結果:
<class 'pandas.indexes.multi.MultiIndex'>
MultiIndex(levels=[['a', 'b', 'c', 'd'], [0, 1, 2]],
labels=[[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]])
選取子集
- 根據索引獲取數據。因爲現在有兩層索引,當通過外層索引獲取數據的時候,可以直接利用外層索引的標籤來獲取。
- 當要通過內層索引獲取數據的時候,在list中傳入兩個元素,前者是表示要選取的外層索引,後者表示要選取的內層索引。
1. 外層選取:
ser_obj[‘outer_label’]
示例代碼:
# 外層選取
print(ser_obj['c'])
運行結果:
0 -1.362096
1 1.558091
2 -0.452313
dtype: float64
2. 內層選取:
ser_obj[:, ‘inner_label’]
示例代碼:
# 內層選取
print(ser_obj[:, 2])
運行結果:
a 0.826662
b 0.015426
c -0.452313
d -0.051063
dtype: float64
常用於分組操作、透視表的生成等
交換分層順序
1. swaplevel()
.swaplevel( )交換內層與外層索引。
示例代碼:
print(ser_obj.swaplevel())
運行結果:
0 a 0.099174
1 a -0.310414
2 a -0.558047
0 b 1.742445
1 b 1.152924
2 b -0.725332
0 c -0.150638
1 c 0.251660
2 c 0.063387
0 d 1.080605
1 d 0.567547
2 d -0.154148
dtype: float64
交換並排序分層
sortlevel()
.sortlevel( )先對外層索引進行排序,再對內層索引進行排序,默認是升序。
示例代碼:
# 交換並排序分層
print(ser_obj.swaplevel().sortlevel())
運行結果:
0 a 0.099174
b 1.742445
c -0.150638
d 1.080605
1 a -0.310414
b 1.152924
c 0.251660
d 0.567547
2 a -0.558047
b -0.725332
c 0.063387
d -0.154148
dtype: float64