1. 程式人生 > >數據分析工具Pandas

數據分析工具Pandas

ack 函數 peer 夠快 常見 type itcast val power

技術分享圖片

參考學習資料:http://pandas.pydata.org

1.什麽是Pandas?

Pandas的名稱來自於面板數據(panel data)和Python數據分析(data analysis)。

Pandas是一個強大的分析結構化數據的工具集,基於NumPy構建,提供了 高級數據結構 和 數據操作工具,它是使Python成為強大而高效的數據分析環境的重要因素之一。

  • 一個強大的分析和操作大型結構化數據集所需的工具集

  • 基礎是NumPy,提供了高性能矩陣的運算

  • 提供了大量能夠快速便捷地處理數據的函數和方法

  • 應用於數據挖掘,數據分析

  • 提供數據清洗功能

2.Pandas的數據結構

import pandas as pd

Pandas有兩個最主要也是最重要的數據結構: Series 和 DataFrame

Series

Series是一種類似於一維數組的 對象,由一組數據(各種NumPy數據類型)以及一組與之對應的索引(數據標簽)組成。

  • 類似一維數組的對象
  • 由數據和索引組成
    • 索引(index)在左,數據(values)在右
    • 索引是自動創建的

技術分享圖片
series
1. 通過list構建Series
  • 示例代碼:
import pandas as pd
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    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
dtype: int64

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

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

3.Pandas的索引操作

索引對象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,時間戳類型

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

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(type(df_obj[a])) # 返回DataFrame類型

df_obj2 = pd.DataFrame(np.random.randn(5,4))
print(df_obj2[[0]]) # 返回DataFrame類型
print(type(df_obj2[[0]])) # 返回DataFrame類型
  • 運行結果:
0   -0.241678
1   -0.526918
2   -1.074163
3   -0.716816
4    0.368212
Name: a, dtype: float64
<class pandas.core.series.Series>

          0
0  0.893045
1  0.192732
2 -0.380107
3  0.711755
4 -0.698903
<class pandas.core.frame.DataFrame>

3. 不連續索引

df_obj[[‘label1’, ‘label2’]]

  • 示例代碼:
# 不連續索引
print(df_obj[[a,c]])
print(df_obj2[[1, 3]])
  • 運行結果:
          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
          1         3
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])
  • 運行結果:
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的索引操作

標簽的切片索引是包含末尾位置的

4.Pandas的對齊運算

是數據清洗的重要過程,可以按索引對齊進行運算,如果沒對齊的位置則補NaN,最後也可以填充NaN

Series的對齊運算

1. Series 按行、索引對齊

  • 示例代碼:
s1 = pd.Series(range(10, 20), index = range(10))
s2 = pd.Series(range(20, 25), index = range(5))

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