量化分析师的Python日记【第6天:数据处理的瑞士军刀pandas下篇

来源:https://uqer.io/community/share/5514bb11f9f06c12790415b2

第二篇:快速进阶

在上一篇中我们介绍了如何创建并访问pandasSeriesDataFrame型的数据,本篇将介绍如何对pandas数据进行操作,掌握这些操作之后,基本可以处理大多数的数据了。首先,导入本篇中使用到的模块:

  1. import numpy as np
  2. import pandas as pd
  3. from pandas import Series, DataFrame

为了看数据方便一些,我们设置一下输出屏幕的宽度

  1. pd.set_option('display.width', 200)

一、数据创建的其他方式

数据结构的创建不止是上篇中介绍的标准形式,本篇再介绍几种。例如,我们可以创建一个以日期为元素的Series

  1. dates = pd.date_range('20150101', periods=5)
  2. print dates
  3. <class 'pandas.tseries.index.DatetimeIndex'>
  4. [2015-01-01, ..., 2015-01-05]
  5. Length: 5, Freq: D, Timezone: None

将这个日期Series作为索引赋给一个DataFrame

  1. df = pd.DataFrame(np.random.randn(5, 4),index=dates,columns=list('ABCD'))
  2. print df
  3. A B C D
  4. 2015-01-01 -0.168870 0.191945 -0.906788 -1.295211
  5. 2015-01-02 -0.985849 0.312378 -1.513870 -0.876869
  6. 2015-01-03 -0.241945 1.437763 0.209494 0.061032
  7. 2015-01-04 0.139199 0.124118 -0.204801 -1.745327
  8. 2015-01-05 0.243644 -0.373126 0.333583 2.640955

只要是能转换成Series的对象,都可以用于创建DataFrame

  1. df2 = pd.DataFrame({ 'A' : 1., 'B': pd.Timestamp('20150214'), 'C': pd.Series(1.6,index=list(range(4)),dtype='float64'), 'D' : np.array([4] * 4, dtype='int64'), 'E' : 'hello pandas!' })
  2. print df2
  3. A B C D E
  4. 0 1 2015-02-14 1.6 4 hello pandas!
  5. 1 1 2015-02-14 1.6 4 hello pandas!
  6. 2 1 2015-02-14 1.6 4 hello pandas!
  7. 3 1 2015-02-14 1.6 4 hello pandas!

二、数据的查看

在多数情况下,数据并不由分析数据的人员生成,而是通过数据接口、外部文件或者其他方式获取。这里我们通过量化实验室的数据接口获取一份数据作为示例:

  1. stock_list = ['000001.XSHE', '000002.XSHE', '000568.XSHE', '000625.XSHE', '000768.XSHE', '600028.XSHG', '600030.XSHG', '601111.XSHG', '601390.XSHG', '601998.XSHG']
  2. raw_data = DataAPI.MktEqudGet(secID=stock_list, beginDate='20150101', endDate='20150131', pandas='1')
  3. df = raw_data[['secID', 'tradeDate', 'secShortName', 'openPrice', 'highestPrice', 'lowestPrice', 'closePrice', 'turnoverVol']]

以上代码获取了2015年一月份全部的交易日内十支股票的日行情信息,首先我们来看一下数据的大小:

  1. print df.shape
  2. (200, 8)

我们可以看到有200行,表示我们获取到了200条记录,每条记录有8个字段,现在预览一下数据,dataframe.head()dataframe.tail()可以查看数据的头五行和尾五行,若需要改变行数,可在括号内指定:

  1. print "Head of this DataFrame:"
  2. print df.head()
  3. print "Tail of this DataFrame:"
  4. print df.tail(3)
  5. Head of this DataFrame:
  6. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  7. 0 000001.XSHE 2015-01-05 平安银行 15.99 16.28 15.60 16.02 286043643
  8. 1 000001.XSHE 2015-01-06 平安银行 15.85 16.39 15.55 15.78 216642140
  9. 2 000001.XSHE 2015-01-07 平安银行 15.56 15.83 15.30 15.48 170012067
  10. 3 000001.XSHE 2015-01-08 平安银行 15.50 15.57 14.90 14.96 140771421
  11. 4 000001.XSHE 2015-01-09 平安银行 14.90 15.87 14.71 15.08 250850023
  12. Tail of this DataFrame:
  13. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  14. 197 601998.XSHG 2015-01-28 中信银行 7.04 7.32 6.95 7.15 163146128
  15. 198 601998.XSHG 2015-01-29 中信银行 6.97 7.05 6.90 7.01 93003445
  16. 199 601998.XSHG 2015-01-30 中信银行 7.10 7.14 6.92 6.95 68146718

dataframe.describe()提供了DataFrame中纯数值数据的统计信息:

  1. print df.describe()
  2. openPrice highestPrice lowestPrice closePrice turnoverVol
  3. count 200.00000 200.000000 200.00000 200.000000 2.000000e+02
  4. mean 15.17095 15.634000 14.86545 15.242750 2.384811e+08
  5. std 7.72807 7.997345 7.56136 7.772184 2.330510e+08
  6. min 6.14000 6.170000 6.02000 6.030000 1.242183e+07
  7. 25% 8.09500 8.250000 7.98750 8.127500 7.357002e+07
  8. 50% 13.96000 14.335000 13.75500 13.925000 1.554569e+08
  9. 75% 19.95000 20.500000 19.46250 20.012500 3.358617e+08
  10. max 36.40000 37.250000 34.68000 36.150000 1.310855e+09

对数据的排序将便利我们观察数据,DataFrame提供了两种形式的排序。一种是按行列排序,即按照索引(行名)或者列名进行排序,可调用dataframe.sort_index,指定axis=0表示按索引(行名)排序,axis=1表示按列名排序,并可指定升序或者降序:

  1. print "Order by column names, descending:"
  2. print df.sort_index(axis=1, ascending=False).head()
  3. Order by column names, descending:
  4. turnoverVol tradeDate secShortName secID openPrice lowestPrice highestPrice closePrice
  5. 0 286043643 2015-01-05 平安银行 000001.XSHE 15.99 15.60 16.28 16.02
  6. 1 216642140 2015-01-06 平安银行 000001.XSHE 15.85 15.55 16.39 15.78
  7. 2 170012067 2015-01-07 平安银行 000001.XSHE 15.56 15.30 15.83 15.48
  8. 3 140771421 2015-01-08 平安银行 000001.XSHE 15.50 14.90 15.57 14.96
  9. 4 250850023 2015-01-09 平安银行 000001.XSHE 14.90 14.71 15.87 15.08

第二种排序是按值排序,可指定列名和排序方式,默认的是升序排序:

  1. print "Order by column value, ascending:"
  2. print df.sort(columns='tradeDate').head()
  3. print "Order by multiple columns value:"
  4. df = df.sort(columns=['tradeDate', 'secID'], ascending=[False, True])
  5. print df.head()
  6. Order by column value, ascending:
  7. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  8. 0 000001.XSHE 2015-01-05 平安银行 15.99 16.28 15.60 16.02 286043643
  9. 20 000002.XSHE 2015-01-05 万科A 14.39 15.29 14.22 14.91 656083570
  10. 40 000568.XSHE 2015-01-05 泸州老窖 20.50 21.99 20.32 21.90 59304755
  11. 60 000625.XSHE 2015-01-05 长安汽车 16.40 18.07 16.32 18.07 82087982
  12. 80 000768.XSHE 2015-01-05 中航飞机 18.76 19.88 18.41 19.33 84199357
  13. Order by multiple columns value:
  14. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  15. 19 000001.XSHE 2015-01-30 平安银行 13.93 14.12 13.76 13.93 93011669
  16. 39 000002.XSHE 2015-01-30 万科A 13.09 13.49 12.80 13.12 209624706
  17. 59 000568.XSHE 2015-01-30 泸州老窖 19.15 19.51 19.11 19.12 14177179
  18. 79 000625.XSHE 2015-01-30 长安汽车 19.16 19.45 18.92 19.18 21233495
  19. 99 000768.XSHE 2015-01-30 中航飞机 25.38 25.65 24.28 24.60 59550293

三、数据的访问和操作

3.1 再谈数据的访问

上篇中已经介绍了使用locilocatiatix以及[]访问DataFrame数据的几种方式,这里再介绍一种方法,使用:来获取部行或者全部列:

  1. print df.iloc[1:4][:]
  2. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  3. 39 000002.XSHE 2015-01-30 万科A 13.09 13.49 12.80 13.12 209624706
  4. 59 000568.XSHE 2015-01-30 泸州老窖 19.15 19.51 19.11 19.12 14177179
  5. 79 000625.XSHE 2015-01-30 长安汽车 19.16 19.45 18.92 19.18 21233495

我们可以扩展上篇介绍的使用布尔类型的向量获取数据的方法,可以很方便地过滤数据,例如,我们要选出收盘价在均值以上的数据:

  1. print df[df.closePrice > df.closePrice.mean()].head()
  2. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  3. 59 000568.XSHE 2015-01-30 泸州老窖 19.15 19.51 19.11 19.12 14177179
  4. 79 000625.XSHE 2015-01-30 长安汽车 19.16 19.45 18.92 19.18 21233495
  5. 99 000768.XSHE 2015-01-30 中航飞机 25.38 25.65 24.28 24.60 59550293
  6. 139 600030.XSHG 2015-01-30 中信证券 28.50 28.72 27.78 27.86 304218245
  7. 58 000568.XSHE 2015-01-29 泸州老窖 19.04 19.23 19.00 19.15 12421826

isin()函数可方便地过滤DataFrame中的数据:

  1. print df[df['secID'].isin(['601628.XSHG', '000001.XSHE', '600030.XSHG'])].head()
  2. print df.shape
  3. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  4. 19 000001.XSHE 2015-01-30 平安银行 13.93 14.12 13.76 13.93 93011669
  5. 139 600030.XSHG 2015-01-30 中信证券 28.50 28.72 27.78 27.86 304218245
  6. 18 000001.XSHE 2015-01-29 平安银行 13.82 14.01 13.75 13.90 101675329
  7. 138 600030.XSHG 2015-01-29 中信证券 28.10 28.58 27.81 28.18 386310957
  8. 17 000001.XSHE 2015-01-28 平安银行 13.87 14.30 13.80 14.06 124087755
  9. (200, 8)

3.2 处理缺失数据

在访问数据的基础上,我们可以更改数据,例如,修改某些元素为缺失值:

  1. df['openPrice'][df['secID'] == '000001.XSHE'] = np.nan
  2. df['highestPrice'][df['secID'] == '601111.XSHG'] = np.nan
  3. df['lowestPrice'][df['secID'] == '601111.XSHG'] = np.nan
  4. df['closePrice'][df['secID'] == '000002.XSHE'] = np.nan
  5. df['turnoverVol'][df['secID'] == '601111.XSHG'] = np.nan
  6. print df.head(10)
  7. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  8. 19 000001.XSHE 2015-01-30 平安银行 NaN 14.12 13.76 13.93 93011669
  9. 39 000002.XSHE 2015-01-30 万科A 13.09 13.49 12.80 NaN 209624706
  10. 59 000568.XSHE 2015-01-30 泸州老窖 19.15 19.51 19.11 19.12 14177179
  11. 79 000625.XSHE 2015-01-30 长安汽车 19.16 19.45 18.92 19.18 21233495
  12. 99 000768.XSHE 2015-01-30 中航飞机 25.38 25.65 24.28 24.60 59550293
  13. 119 600028.XSHG 2015-01-30 中国石化 6.14 6.17 6.02 6.03 502445638
  14. 139 600030.XSHG 2015-01-30 中信证券 28.50 28.72 27.78 27.86 304218245
  15. 159 601111.XSHG 2015-01-30 中国国航 7.92 NaN NaN 7.69 NaN
  16. 179 601390.XSHG 2015-01-30 中国中铁 8.69 8.69 8.12 8.14 352357431
  17. 199 601998.XSHG 2015-01-30 中信银行 7.10 7.14 6.92 6.95 68146718

原始数据的中很可能存在一些数据的缺失,就如同现在处理的这个样例数据一样,处理缺失数据有多种方式。通常使用dataframe.dropna()dataframe.dropna()可以按行丢弃带有nan的数据;若指定how='all'(默认是'any'),则只在整行全部是nan时丢弃数据;若指定thresh,则表示当某行数据非缺失列数超过指定数值时才保留;要指定根据某列丢弃可以通过subset完成。

  1. print "Data size before filtering:"
  2. print df.shape
  3. print "Drop all rows that have any NaN values:"
  4. print "Data size after filtering:"
  5. print df.dropna().shape
  6. print df.dropna().head(10)
  7. print "Drop only if all columns are NaN:"
  8. print "Data size after filtering:"
  9. print df.dropna(how='all').shape
  10. print df.dropna(how='all').head(10)
  11. print "Drop rows who do not have at least six values that are not NaN"
  12. print "Data size after filtering:"
  13. print df.dropna(thresh=6).shape
  14. print df.dropna(thresh=6).head(10)
  15. print "Drop only if NaN in specific column:"
  16. print "Data size after filtering:"
  17. print df.dropna(subset=['closePrice']).shape
  18. print df.dropna(subset=['closePrice']).head(10)
  19. Data size before filtering:
  20. (200, 8)
  21. Drop all rows that have any NaN values:
  22. Data size after filtering:
  23. (140, 8)
  24. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  25. 59 000568.XSHE 2015-01-30 泸州老窖 19.15 19.51 19.11 19.12 14177179
  26. 79 000625.XSHE 2015-01-30 长安汽车 19.16 19.45 18.92 19.18 21233495
  27. 99 000768.XSHE 2015-01-30 中航飞机 25.38 25.65 24.28 24.60 59550293
  28. 119 600028.XSHG 2015-01-30 中国石化 6.14 6.17 6.02 6.03 502445638
  29. 139 600030.XSHG 2015-01-30 中信证券 28.50 28.72 27.78 27.86 304218245
  30. 179 601390.XSHG 2015-01-30 中国中铁 8.69 8.69 8.12 8.14 352357431
  31. 199 601998.XSHG 2015-01-30 中信银行 7.10 7.14 6.92 6.95 68146718
  32. 58 000568.XSHE 2015-01-29 泸州老窖 19.04 19.23 19.00 19.15 12421826
  33. 78 000625.XSHE 2015-01-29 长安汽车 19.60 19.64 18.90 19.24 25546060
  34. 98 000768.XSHE 2015-01-29 中航飞机 24.65 25.63 24.53 24.98 67095945
  35. Drop only if all columns are NaN:
  36. Data size after filtering:
  37. (200, 8)
  38. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  39. 19 000001.XSHE 2015-01-30 平安银行 NaN 14.12 13.76 13.93 93011669
  40. 39 000002.XSHE 2015-01-30 万科A 13.09 13.49 12.80 NaN 209624706
  41. 59 000568.XSHE 2015-01-30 泸州老窖 19.15 19.51 19.11 19.12 14177179
  42. 79 000625.XSHE 2015-01-30 长安汽车 19.16 19.45 18.92 19.18 21233495
  43. 99 000768.XSHE 2015-01-30 中航飞机 25.38 25.65 24.28 24.60 59550293
  44. 119 600028.XSHG 2015-01-30 中国石化 6.14 6.17 6.02 6.03 502445638
  45. 139 600030.XSHG 2015-01-30 中信证券 28.50 28.72 27.78 27.86 304218245
  46. 159 601111.XSHG 2015-01-30 中国国航 7.92 NaN NaN 7.69 NaN
  47. 179 601390.XSHG 2015-01-30 中国中铁 8.69 8.69 8.12 8.14 352357431
  48. 199 601998.XSHG 2015-01-30 中信银行 7.10 7.14 6.92 6.95 68146718
  49. Drop rows who do not have at least six values that are not NaN
  50. Data size after filtering:
  51. (180, 8)
  52. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  53. 19 000001.XSHE 2015-01-30 平安银行 NaN 14.12 13.76 13.93 93011669
  54. 39 000002.XSHE 2015-01-30 万科A 13.09 13.49 12.80 NaN 209624706
  55. 59 000568.XSHE 2015-01-30 泸州老窖 19.15 19.51 19.11 19.12 14177179
  56. 79 000625.XSHE 2015-01-30 长安汽车 19.16 19.45 18.92 19.18 21233495
  57. 99 000768.XSHE 2015-01-30 中航飞机 25.38 25.65 24.28 24.60 59550293
  58. 119 600028.XSHG 2015-01-30 中国石化 6.14 6.17 6.02 6.03 502445638
  59. 139 600030.XSHG 2015-01-30 中信证券 28.50 28.72 27.78 27.86 304218245
  60. 179 601390.XSHG 2015-01-30 中国中铁 8.69 8.69 8.12 8.14 352357431
  61. 199 601998.XSHG 2015-01-30 中信银行 7.10 7.14 6.92 6.95 68146718
  62. 18 000001.XSHE 2015-01-29 平安银行 NaN 14.01 13.75 13.90 101675329
  63. Drop only if NaN in specific column:
  64. Data size after filtering:
  65. (180, 8)
  66. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  67. 19 000001.XSHE 2015-01-30 平安银行 NaN 14.12 13.76 13.93 93011669
  68. 59 000568.XSHE 2015-01-30 泸州老窖 19.15 19.51 19.11 19.12 14177179
  69. 79 000625.XSHE 2015-01-30 长安汽车 19.16 19.45 18.92 19.18 21233495
  70. 99 000768.XSHE 2015-01-30 中航飞机 25.38 25.65 24.28 24.60 59550293
  71. 119 600028.XSHG 2015-01-30 中国石化 6.14 6.17 6.02 6.03 502445638
  72. 139 600030.XSHG 2015-01-30 中信证券 28.50 28.72 27.78 27.86 304218245
  73. 159 601111.XSHG 2015-01-30 中国国航 7.92 NaN NaN 7.69 NaN
  74. 179 601390.XSHG 2015-01-30 中国中铁 8.69 8.69 8.12 8.14 352357431
  75. 199 601998.XSHG 2015-01-30 中信银行 7.10 7.14 6.92 6.95 68146718
  76. 18 000001.XSHE 2015-01-29 平安银行 NaN 14.01 13.75 13.90 101675329

有数据缺失时也未必是全部丢弃,dataframe.fillna(value=value)可以指定填补缺失值的数值

  1. print df.fillna(value=20150101).head()
  2. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  3. 19 000001.XSHE 2015-01-30 平安银行 20150101.00 14.12 13.76 13.93 93011669
  4. 39 000002.XSHE 2015-01-30 万科A 13.09 13.49 12.80 20150101.00 209624706
  5. 59 000568.XSHE 2015-01-30 泸州老窖 19.15 19.51 19.11 19.12 14177179
  6. 79 000625.XSHE 2015-01-30 长安汽车 19.16 19.45 18.92 19.18 21233495
  7. 99 000768.XSHE 2015-01-30 中航飞机 25.38 25.65 24.28 24.60 59550293

3.3 数据操作

SeriesDataFrame的类函数提供了一些函数,如mean()sum()等,指定0按列进行,指定1按行进行:

  1. df = raw_data[['secID', 'tradeDate', 'secShortName', 'openPrice', 'highestPrice', 'lowestPrice', 'closePrice', 'turnoverVol']]
  2. print df.mean(0)
  3. openPrice 1.517095e+01
  4. highestPrice 1.563400e+01
  5. lowestPrice 1.486545e+01
  6. closePrice 1.524275e+01
  7. turnoverVol 2.384811e+08
  8. dtype: float64

value_counts函数可以方便地统计频数:

  1. print df['closePrice'].value_counts().head()
  2. 6.58 3
  3. 13.12 2
  4. 9.13 2
  5. 8.58 2
  6. 6.93 2
  7. dtype: int64

panda中,Series可以调用map函数来对每个元素应用一个函数,DataFrame可以调用apply函数对每一列(行)应用一个函数,applymap对每个元素应用一个函数。这里面的函数可以是用户自定义的一个lambda函数,也可以是已有的其他函数。下例展示了将收盘价调整到[0, 1]区间:

  1. print df[['closePrice']].apply(lambda x: (x - x.min()) / (x.max() - x.min())).head()
  2. closePrice
  3. 0 0.331673
  4. 1 0.323705
  5. 2 0.313745
  6. 3 0.296481
  7. 4 0.300465

使用append可以在Series后添加元素,以及在DataFrame尾部添加一行:

  1. dat1 = df[['secID', 'tradeDate', 'closePrice']].head()
  2. dat2 = df[['secID', 'tradeDate', 'closePrice']].iloc[2]
  3. print "Before appending:"
  4. print dat1
  5. dat = dat1.append(dat2, ignore_index=True)
  6. print "After appending:"
  7. print dat
  8. Before appending:
  9. secID tradeDate closePrice
  10. 0 000001.XSHE 2015-01-05 16.02
  11. 1 000001.XSHE 2015-01-06 15.78
  12. 2 000001.XSHE 2015-01-07 15.48
  13. 3 000001.XSHE 2015-01-08 14.96
  14. 4 000001.XSHE 2015-01-09 15.08
  15. After appending:
  16. secID tradeDate closePrice
  17. 0 000001.XSHE 2015-01-05 16.02
  18. 1 000001.XSHE 2015-01-06 15.78
  19. 2 000001.XSHE 2015-01-07 15.48
  20. 3 000001.XSHE 2015-01-08 14.96
  21. 4 000001.XSHE 2015-01-09 15.08
  22. 5 000001.XSHE 2015-01-07 15.48

DataFrame可以像在SQL中一样进行合并,在上篇中,我们介绍了使用concat函数创建DataFrame,这就是一种合并的方式。另外一种方式使用merge函数,需要指定依照哪些列进行合并,下例展示了如何根据security ID和交易日合并数据:

  1. dat1 = df[['secID', 'tradeDate', 'closePrice']]
  2. dat2 = df[['secID', 'tradeDate', 'turnoverVol']]
  3. dat = dat1.merge(dat2, on=['secID', 'tradeDate'])
  4. print "The first DataFrame:"
  5. print dat1.head()
  6. print "The second DataFrame:"
  7. print dat2.head()
  8. print "Merged DataFrame:"
  9. print dat.head()
  10. The first DataFrame:
  11. secID tradeDate closePrice
  12. 0 000001.XSHE 2015-01-05 16.02
  13. 1 000001.XSHE 2015-01-06 15.78
  14. 2 000001.XSHE 2015-01-07 15.48
  15. 3 000001.XSHE 2015-01-08 14.96
  16. 4 000001.XSHE 2015-01-09 15.08
  17. The second DataFrame:
  18. secID tradeDate turnoverVol
  19. 0 000001.XSHE 2015-01-05 286043643
  20. 1 000001.XSHE 2015-01-06 216642140
  21. 2 000001.XSHE 2015-01-07 170012067
  22. 3 000001.XSHE 2015-01-08 140771421
  23. 4 000001.XSHE 2015-01-09 250850023
  24. Merged DataFrame:
  25. secID tradeDate closePrice turnoverVol
  26. 0 000001.XSHE 2015-01-05 16.02 286043643
  27. 1 000001.XSHE 2015-01-06 15.78 216642140
  28. 2 000001.XSHE 2015-01-07 15.48 170012067
  29. 3 000001.XSHE 2015-01-08 14.96 140771421
  30. 4 000001.XSHE 2015-01-09 15.08 250850023

DataFrame另一个强大的函数是groupby,可以十分方便地对数据分组处理,我们对2015年一月内十支股票的开盘价,最高价,最低价,收盘价和成交量求平均值:

  1. df_grp = df.groupby('secID')
  2. grp_mean = df_grp.mean()
  3. print grp_mean
  4. openPrice highestPrice lowestPrice closePrice turnoverVol
  5. secID
  6. 000001.XSHE 14.6550 14.9840 14.4330 14.6650 154710615
  7. 000002.XSHE 13.3815 13.7530 13.0575 13.4100 277459431
  8. 000568.XSHE 19.7220 20.1015 19.4990 19.7935 29199107
  9. 000625.XSHE 19.4915 20.2275 19.1040 19.7170 42633332
  10. 000768.XSHE 22.4345 23.4625 21.8830 22.6905 92781199
  11. 600028.XSHG 6.6060 6.7885 6.4715 6.6240 531966632
  12. 600030.XSHG 31.1505 32.0825 30.4950 31.2325 611544509
  13. 601111.XSHG 8.4320 8.6520 8.2330 8.4505 104143358
  14. 601390.XSHG 8.4060 8.6625 8.2005 8.4100 362831455
  15. 601998.XSHG 7.4305 7.6260 7.2780 7.4345 177541066

如果希望取每只股票的最新数据,应该怎么操作呢?drop_duplicates可以实现这个功能,首先对数据按日期排序,再按security ID去重:

  1. df2 = df.sort(columns=['secID', 'tradeDate'], ascending=[True, False])
  2. print df2.drop_duplicates(subset='secID')
  3. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  4. 19 000001.XSHE 2015-01-30 平安银行 13.93 14.12 13.76 13.93 93011669
  5. 39 000002.XSHE 2015-01-30 万科A 13.09 13.49 12.80 13.12 209624706
  6. 59 000568.XSHE 2015-01-30 泸州老窖 19.15 19.51 19.11 19.12 14177179
  7. 79 000625.XSHE 2015-01-30 长安汽车 19.16 19.45 18.92 19.18 21233495
  8. 99 000768.XSHE 2015-01-30 中航飞机 25.38 25.65 24.28 24.60 59550293
  9. 119 600028.XSHG 2015-01-30 中国石化 6.14 6.17 6.02 6.03 502445638
  10. 139 600030.XSHG 2015-01-30 中信证券 28.50 28.72 27.78 27.86 304218245
  11. 159 601111.XSHG 2015-01-30 中国国航 7.92 8.03 7.65 7.69 61877792
  12. 179 601390.XSHG 2015-01-30 中国中铁 8.69 8.69 8.12 8.14 352357431
  13. 199 601998.XSHG 2015-01-30 中信银行 7.10 7.14 6.92 6.95 68146718

若想要保留最老的数据,可以在降序排列后取最后一个记录,通过指定take_last=True(默认值为False,取第一条记录)可以实现:

  1. print df2.drop_duplicates(subset='secID', take_last=True)
  2. secID tradeDate secShortName openPrice highestPrice lowestPrice closePrice turnoverVol
  3. 0 000001.XSHE 2015-01-05 平安银行 15.99 16.28 15.60 16.02 286043643
  4. 20 000002.XSHE 2015-01-05 万科A 14.39 15.29 14.22 14.91 656083570
  5. 40 000568.XSHE 2015-01-05 泸州老窖 20.50 21.99 20.32 21.90 59304755
  6. 60 000625.XSHE 2015-01-05 长安汽车 16.40 18.07 16.32 18.07 82087982
  7. 80 000768.XSHE 2015-01-05 中航飞机 18.76 19.88 18.41 19.33 84199357
  8. 100 600028.XSHG 2015-01-05 中国石化 6.59 7.14 6.45 7.14 1186499645
  9. 120 600030.XSHG 2015-01-05 中信证券 33.90 35.25 33.01 34.66 698627215
  10. 140 601111.XSHG 2015-01-05 中国国航 7.98 8.62 7.98 8.62 231611758
  11. 160 601390.XSHG 2015-01-05 中国中铁 9.37 9.37 8.90 9.13 469902172
  12. 180 601998.XSHG 2015-01-05 中信银行 8.15 8.33 7.91 8.16 337368242

四、数据可视化

pandas数据直接可以绘图查看,下例中我们采用中国石化一月的收盘价进行绘图,其中set_index('tradeDate')['closePrice']表示将DataFrame'tradeDate'这一列作为索引,将'closePrice'这一列作为Series的值,返回一个Series对象,随后调用plot函数绘图,更多的参数可以在matplotlib的文档中查看。

  1. dat = df[df['secID'] == '600028.XSHG'].set_index('tradeDate')['closePrice']
  2. dat.plot(title="Close Price of SINOPEC (600028) during Jan, 2015")
  3. <matplotlib.axes.AxesSubplot at 0x49b6510>

量化分析师的Python日记【第6天:数据处理的瑞士军刀pandas下篇 - 图1