Pandas Dataframe - 查找错误

时间:2016-08-01 18:59:00

标签: python pandas

我正在尝试使用日期和股票代码组合在pandas(版本0.14.1)数据框中查找一行,并且收到一个奇怪的错误。

我的pandas数据框如下所示:

                         AAPL     IBM    GOOG    XOM       Date
2011-01-10 16:00:00  340.99  143.41  614.21  72.02 2011-01-10
2011-01-11 16:00:00  340.18  143.06  616.01  72.56 2011-01-11
2011-01-12 16:00:00  342.95  144.82  616.87  73.41 2011-01-12
2011-01-13 16:00:00  344.20  144.55  616.69  73.54 2011-01-13
2011-01-14 16:00:00  346.99  145.70  624.18  74.62 2011-01-14
2011-01-18 16:00:00  339.19  146.33  639.63  75.45 2011-01-18
2011-01-19 16:00:00  337.39  151.22  631.75  75.00 2011-01-19

当我尝试使用日期/字符串组合进行查找时,收到以下错误:

>>> df_data.lookup(date,ticker)
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2820, in run_code
    exec code_obj in self.user_global_ns, self.user_ns
  File "<ipython-input-2-31ab981e2184>", line 1, in <module>
    df_data.lookup(date,ticker)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 2207, in lookup
    n = len(row_labels)
TypeError: object of type 'datetime.datetime' has no len()

从我在pandas文档中看到的情况来看,这应该可行并且我的日期变量是一个常规日期时间

>>> date
Out[5]: datetime.datetime(2011, 1, 10, 16, 0)

我做的事情显然不正确吗?

1 个答案:

答案 0 :(得分:4)

df.lookup需要2个数组(而不是标量)作为参数:

In [25]: df.lookup(row_labels=[DT.datetime(2011,1,10,16,0)], col_labels=['AAPL'])
Out[25]: array([ 340.99])

如果您只想查找一个值,请改用df.get_value

In [30]: df.get_value(DT.datetime(2011,1,10,16,0), 'AAPL')
Out[30]: 340.99000000000001