pandas-利用python進行數據分析

pandas簡介

pandas 是基於NumPy 的一種工具,該工具是爲了解決數據分析任務而創建的。Pandas 納入了大量庫和一些標準的數據模型,提供了高效地操作大型數據集所需的工具,pandas提供了大量能使我們快速便捷地處理數據的函數和方法。

數據結構

  • Series:一維數組,與Numpy中的一維array類似。二者與Python基本的數據結構List也很相近,其區別是:List中的元素可以是不同的數據類型,而Array和Series中則只允許存儲相同的數據類型,這樣可以更有效的使用內存,提高運算效率。


  • Time- Series:以時間爲索引的Series。


  • DataFrame:二維的表格型數據結構。很多功能與R中的data.frame類似。可以將DataFrame理解爲Series的容器。以下的內容主要以DataFrame爲主。


重新索引

pandas一個重要的方法是重新索引,創建一個新索引的新對象。(方法我只應用一遍,其他自己多加思考:如series.reindex(range(8),method='ffill') 還可以series.reindex(range(8),method='bfill'))

  
  
  
  1. series=pd.Series([1,2,3,4,5,6,7],index=['less0','less1','less2','less3','less4','less5','less6'])

  2. less0    1

  3. less1    2

  4. less2    3

  5. less3    4

  6. less4    5

  7. less5    6

  8. less6    7

  9. dtype: int64

  10. series.reindex(['less1','less0','less2','less3','less4','less5','less6','b'])

  11. less1    2.0

  12. less0    1.0

  13. less2    3.0

  14. less3    4.0

  15. less4    5.0

  16. less5    6.0

  17. less6    7.0

  18. b        NaN

  19. dtype: float64

  20. series.reindex(['12','211'])

  21. 12    NaN

  22. 211   NaN

  23. dtype: float64

  24. series.reindex(['12','211'],fill_value=0)

  25. 12     0

  26. 211    0

  27. dtype: int64

  28. series=pd.Series([1,2,3,4,5,6])

  29. series.reindex(range(8),method='ffill')

  30. 0    1

  31. 1    2

  32. 2    3

  33. 3    4

  34. 4    5

  35. 5    6

  36. 6    6

  37. 7    6

  38. dtype: int64

  39. dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=['a','b','c','d'])

  40. dataframe

  41. In [3]: dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=['a','b','c','d'])

  42.   ...: dataframe

  43.   ...:

  44. Out[3]:

  45.    a   b   c   d

  46. 1   0   1   2   3

  47. 2   4   5   6   7

  48. 3   8   9  10  11

  49. 4  12  13  14  15

  50. In [4]: dataframe.reindex(index=[2,1,3,4],columns=['c','b','a','d'])

  51. Out[4]:

  52.    c   b   a   d

  53. 2   6   5   4   7

  54. 1   2   1   0   3

  55. 3  10   9   8  11

  56. 4  14  13  12  15

  57. In [5]: dataframe.reindex(index=[2,1,3,4],columns=['c','b','a','d','e'])

  58. Out[5]:

  59.      c     b     a     d   e

  60. 2   6.0   5.0   4.0   7.0 NaN

  61. 1   2.0   1.0   0.0   3.0 NaN

  62. 3  10.0   9.0   8.0  11.0 NaN

  63. 4  14.0  13.0  12.0  15.0 NaN

  64. In [6]: dataframe.reindex(index=[2,1,3,4],columns=['c','b','a','d','e'],method='ffill')

  65. Out[6]:

  66.    c   b   a   d   e

  67. 2   6   5   4   7   7

  68. 1   2   1   0   3   3

  69. 3  10   9   8  11  11

  70. 4  14  13  12  15  15

  71. In [7]: dataframe.reindex(index=[2,1,3,4],columns=['c','b','a','d','e'],method='bfill')

  72. Out[7]:

  73.    c   b   a   d   e

  74. 2   6   5   4   7 NaN

  75. 1   2   1   0   3 NaN

  76. 3  10   9   8  11 NaN

  77. 4  14  13  12  15 NaN

  78. In [8]: dataframe.reindex(index=[2,1,3,4],columns=['c','b','a','d','e'],method='bfill',fill_value=0)

  79. Out[8]:

  80.    c   b   a   d  e

  81. 2   6   5   4   7  0

  82. 1   2   1   0   3  0

  83. 3  10   9   8  11  0

  84. 4  14  13  12  15  0

  85. #copy 默認是true 怎樣都複製,false的時候新舊相等不復制

  86. In [9]: dataframe.reindex(index=[2,1,3,4],columns=['c','b','a','d','e'],method='bfill',fill_value=0,copy=True)

  87. Out[9]:

  88.    c   b   a   d  e

  89. 2   6   5   4   7  0

  90. 1   2   1   0   3  0

  91. 3  10   9   8  11  0

  92. 4  14  13  12  15  0

丟棄指定軸上的數據

  
  
  
  1. series=pd.Series([1,2,3,4,5,6,7],index=['less0','less1','less2','less3','less4','less5','less6'])

  2. series.drop(['less1','less0','less2'])

  3. less3    4

  4. less4    5

  5. less5    6

  6. less6    7

  7. dtype: int64

  8. In [10]: dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=['a','b','c','d'])

  9.    ...: dataframe.drop([1,2])

  10.    ...:

  11. Out[10]:

  12.    a   b   c   d

  13. 3   8   9  10  11

  14. 4  12  13  14  15

  15. In [11]: dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=['a','b','c','d'])

  16.    ...: dataframe.drop(columns=['a','b'],index=[1,2])

  17.    ...:

  18. Out[11]:

  19.    c   d

  20. 3  10  11

  21. 4  14  15

索引選取過濾

  
  
  
  1. series=pd.Series([1,2,3,4,5,6])

  2. series

  3. 0    1

  4. 1    2

  5. 2    3

  6. 3    4

  7. 4    5

  8. 5    6

  9. dtype: int64

  10. In [12]: series=pd.Series([1,2,3,4,5,6])

  11.    ...: series[series>2]

  12.    ...:

  13. Out[12]:

  14. 2    3

  15. 3    4

  16. 4    5

  17. 5    6

  18. dtype: int64

  19. In [13]:     series=pd.Series([1,2,3,4,5,6])

  20.     ...:    series[2]

  21.    ...:

  22. Out[13]: 3

  23. series=pd.Series([1,2,3,4,5,6])

  24. series[2:5]

  25. 2    3

  26. 3    4

  27. 4    5

  28. dtype: int64

  29. series=pd.Series([1,2,3,4,5,6])

  30. series[2:5]=7

  31. series

  32. 0    1

  33. 1    2

  34. 2    7

  35. 3    7

  36. 4    7

  37. 5    6

  38. dtype: int64

  39. In [14]: dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=['a','b','c','d'])

  40.    ...: dataframe

  41.    ...:

  42. Out[14]:

  43.    a   b   c   d

  44. 1   0   1   2   3

  45. 2   4   5   6   7

  46. 3   8   9  10  11

  47. 4  12  13  14  15

  48. In [16]: dataframe.loc[[1,2,3],['a','c']]

  49. Out[16]:

  50.   a   c

  51. 1  0   2

  52. 2  4   6

  53. 3  8  10

  54. In [17]: dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=['a','b','c','d'])

  55.    ...: dataframe[dataframe['a']>3]

  56.    ...:

  57. Out[17]:

  58.    a   b   c   d

  59. 2   4   5   6   7

  60. 3   8   9  10  11

  61. 4  12  13  14  15

  62. In [18]: dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=['a','b','c','d'])

  63.    ...: dataframe[dataframe.loc[[1,2,3],['a','c']]>3]

  64.    ...:

  65. Out[18]:

  66.     a   b     c   d

  67. 1  NaN NaN   NaN NaN

  68. 2  4.0 NaN   6.0 NaN

  69. 3  8.0 NaN  10.0 NaN

  70. 4  NaN NaN   NaN NaN

  71. In [20]: dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=['a','b','c','d'])

  72.    ...: dataframe[dataframe<3]=0

  73.    ...: dataframe

  74.    ...:

  75. Out[20]:

  76.    a   b   c   d

  77. 1   0   0   0   3

  78. 2   4   5   6   7

  79. 3   8   9  10  11

  80. 4  12  13  14  15

函數的應用和映射

  
  
  
  1. In [20]: dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=['a','b','c','d'])

  2.    ...: dataframe[dataframe<3]=0

  3.    ...: dataframe

  4.    ...:

  5. Out[20]:

  6.    a   b   c   d

  7. 1   0   0   0   3

  8. 2   4   5   6   7

  9. 3   8   9  10  11

  10. 4  12  13  14  15

  11. In [21]:

  12. In [21]:

  13. In [21]: dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=['a','b','c','d'])

  14.    ...: f=lambda x :x.max()-x.min()

  15.    ...: dataframe.apply(f,axis=1)

  16.    ...:

  17. Out[21]:

  18. 1    3

  19. 2    3

  20. 3    3

  21. 4    3

  22. dtype: int64

  23. In [22]: dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=['a','b','c','d'])

  24.    ...: f=lambda x :x.max()-x.min()

  25.    ...: dataframe.apply(f,axis=0)

  26.    ...:

  27. Out[22]:

  28. a    12

  29. b    12

  30. c    12

  31. d    12

  32. dtype: int64

  33. #應用在元素及的函數

  34. dataframe.applymap(f2)

  35. In [24]: f2=lambda x:x/2

  36. In [25]: dataframe.applymap(f2)

  37. Out[25]:

  38.     a    b    c    d

  39. 1  0.0  0.5  1.0  1.5

  40. 2  2.0  2.5  3.0  3.5

  41. 3  4.0  4.5  5.0  5.5

  42. 4  6.0  6.5  7.0  7.5

  43. #一維數組直接用apply()

  44. series=pd.Series([1,2,3,4,5,6])

  45. series.apply(f2)

  46. 0    0.5

  47. 1    1.0

  48. 2    1.5

  49. 3    2.0

  50. 4    2.5

  51. 5    3.0

  52. dtype: float64

常用函數

df 代表的是任意的Pandas DataFrame對象 s 代表的是任意的Pandas Series對象

  • 導入數據
    pd.read_csv(filename):從CSV文件導入數據

    pd.read_table(filename):從限定分隔符的文本文件導入數據

    pd.read_excel(filename):從Excel文件導入數據

    pd.readsql(query,connectionobject):從SQL表/庫導入數據

    pd.readjson(jsonstring):從JSON格式的字符串導入數據

    pd.read_html(url):解析URL、字符串或者HTML文件,抽取其中的tables表格

    pd.readclipboard():從你的粘貼板獲取內容,並傳給readtable()

    pd.DataFrame(dict):從字典對象導入數據,Key是列名,Value是數據


  • 導出數據 df.to_csv(filename):導出數據到CSV文件

    df.to_excel(filename):導出數據到Excel文件

    df.tosql(tablename,connection_object):導出數據到SQL表

    df.to_json(filename):以Json格式導出數據到文本文件


  • 查看、檢查數據 df.head(n):查看DataFrame對象的前n行

    df.tail(n):查看DataFrame對象的最後n行

    df.shape():查看行數和列數

    http://df.info():查看索引、數據類型和內存信息

    df.describe():查看數值型列的彙總統計

    s.value_counts(dropna=False):查看Series對象的唯一值和計數


  • 數據選取 df[col]:根據列名,並以Series的形式返回列

    df[[col1,col2]]:以DataFrame形式返回多列

    s.iloc[0]:按位置選取數據

    s.loc['index_one']:按索引選取數據

    df.iloc[0,:]:返回第一行

    df.iloc[0,0]:返回第一列的第一個元素


  • 數據清理
    df.columns=['a','b','c']:重命名列名

    pd.isnull():檢查DataFrame對象中的空值,並返回一個Boolean數組

    pd.notnull():檢查DataFrame對象中的非空值,並返回一個Boolean數組

    df.dropna():刪除所有包含空值的行

    df.dropna(axis=1):刪除所有包含空值的列

    df.dropna(axis=1,thresh=n):刪除所有小於n個非空值的行

    df.fillna(x):用x替換DataFrame對象中所有的空值

    s.astype(float):將Series中的數據類型更改爲float類型

    s.replace(1,'one'):用‘one’代替所有等於1的值

    s.replace([1,3],['one','three']):用'one'代替1,用'three'代替3

    df.rename(columns=lambdax:x+1):批量更改列名

    df.rename(columns={'oldname':'new name'}):選擇性更改列名

    df.setindex('columnone'):更改索引列

    df.rename(index=lambdax:x+1):批量重命名索引


  
  
  
  1. In [27]: dataframe=pd.DataFrame(np.arange(16).reshape((4,4)),index=[1,2,3,4],columns=[1,2,3,4])

  2.    ...: dataframe

  3.    ...: dataframe.set_index(4)

  4.    ...:

  5. Out[27]:

  6.     1   2   3

  7. 4

  8. 3    0   1   2

  9. 7    4   5   6

  10. 11   8   9  10

  11. 15  12  13  14

  • 數據處理:Filter、Sort和GroupBy
    df[df[col]>0.5]:選擇col列的值大於0.5的行

    df.sort_values(col1):按照列col1排序數據,默認升序排列

    df.sort_values(col2,ascending=False):按照列col1降序排列數據

    df.sort_values([col1,col2],ascending=[True,False]):先按列col1升序排列,後按col2降序排列數據 df.groupby(col):返回一個按列col進行分組的Groupby對象

    df.groupby([col1,col2]):返回一個按多列進行分組的Groupby對象

    df.groupby(col1)[col2]:返回按列col1進行分組後,列col2的均值 df.pivot_table(index=col1,

    values=[col2,col3],aggfunc=max):創建一個按列col1進行分組,並計算col2和col3的最大值的數據透視表

    df.groupby(col1).agg(np.mean):返回按列col1分組的所有列的均值

    data.apply(np.mean):對DataFrame中的每一列應用函數np.mean

    data.apply(np.max,axis=1):對DataFrame中的每一行應用函數np.max


  • 數據合併
    df1.append(df2):將df2中的行添加到df1的尾部

    pd.concat([df1,df2],axis=1):將df2中的列添加到df1的尾部

    df1.join(df2,on=col1,how='inner'):對df1的列和df2的列執行SQL形式的join


  • 數據統計
    df.describe():查看數據值列的彙總統計

    df.mean():返回所有列的均值

    df.corr():返回列與列之間的相關係數

    df.count():返回每一列中的非空值的個數

    df.max():返回每一列的最大值

    df.min():返回每一列的最小值

    df.median():返回每一列的中位數

    df.std():返回每一列的標準差


層次化索引

  
  
  
  1. pd.Series([1,2,34,5,67,8,90,23,4,5],index=[['one','one','one','two','one','one','three','three','three','three'],[1,2,3,4,5,6,7,8,9,10]])

  2. one    1      1

  3.       2      2

  4.       3     34

  5. two    4      5

  6. one    5     67

  7.       6      8

  8. three  7     90

  9.       8     23

  10.       9      4

  11.       10     5

  12. dtype: int64

  13. series['one']

  14. 1     1

  15. 2     2

  16. 3    34

  17. 5    67

  18. 6     8

  19. dtype: int64

  20. series['one',3]

  21. #重排分級順序

  22. series=pd.Series([1,2,34,5,67,8,90,23,4,5],index=[['one','one','one','two','one','one','three','three','three','three'],[1,2,3,4,5,6,7,8,9,10]])

  23. #同理列也可以指定名稱

  24. series.index.names=['key1','key2']

  25. key1   key2

  26. one    1        1

  27.       2        2

  28.       3       34

  29. two    4        5

  30. one    5       67

  31.       6        8

  32. three  7       90

  33.       8       23

  34.       9        4

  35.       10       5

  36. dtype: int64

  37. series.swaplevel('key2','key1')

  38. key2  key1

  39. 1     one       1

  40. 2     one       2

  41. 3     one      34

  42. 4     two       5

  43. 5     one      67

  44. 6     one       8

  45. 7     three    90

  46. 8     three    23

  47. 9     three     4

  48. 10    three     5

  49. dtype: int64

  50. #更具級別獲取統計數據

  51. series.sum(level='key1')

  52. key1

  53. one      112

  54. two        5

  55. three    122

  56. dtype: int64

  57. series.sum(level='key2')

  58. key2

  59. 1      1

  60. 2      2

  61. 3     34

  62. 4      5

  63. 5     67

  64. 6      8

  65. 7     90

  66. 8     23

  67. 9      4

  68. 10     5

  69. dtype: int64


本文分享自微信公衆號 - 我愛問讀書(wawds_)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章