无法通过名称从numpy数组中获取值

时间:2013-04-05 14:23:12

标签: python arrays numpy

我有以下代码,我试图通过我设置的名称获取数组中的值。

import datetime
import numpy as np
import matplotlib.finance as finance
import matplotlib.mlab as mlab

def get_pxing(my_tickers):
    dt = np.dtype([('sym', np.str_, 6), ('adj_close', np.float32)])
    close_px = []
    for ticker in my_tickers:
    # a numpy record array with fields: date, open, high, low, close, volume, adj_close)
        fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)
        r = mlab.csv2rec(fh)    
        fh.close()
        prices = np.array((ticker, r.adj_close), dtype=dt)
        close_px.append(prices)
    return close_px

enddate = startdate = datetime.date.today() - datetime.timedelta(1)

my_tickers = np.genfromtxt('./stocklist.csv', delimiter = ",", dtype=None, names=True)

data = get_pxing(my_tickers["ticker"])
print data

这很好但是如果我尝试

print data['sym'] 

我明白了:

Traceback (most recent call last):
  File "stockyield.py", line 26, in <module>
    print data['sym']
TypeError: list indices must be integers, not str

也许我已经使用close_px.append转换了我的数组,但是,我无法弄清楚如何使用np.append,因为我总是得到数组不匹配。

我的输入csv文件如下:

ticker, holding
T, 100
F, 200

有关最佳方法的任何建议吗?

1 个答案:

答案 0 :(得分:0)

正如评论所说,似乎你正在将一个numpy数组附加到数组列表中。你真的想要创建一个元组列表,然后将元组列表转换为数组。

尝试这样的事情(改变的行有注释)

def get_pxing(my_tickers):
    dt = np.dtype([('sym', np.str_, 6), ('adj_close', np.float32)])
    close_px = []
    for ticker in my_tickers:
    # a numpy record array with fields: date, open, high, low, close, volume, adj_close)
        fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)
        r = mlab.csv2rec(fh)    
        fh.close()
        prices = (ticker, r.adj_close)   # append a tuple to your list instead of an array
        close_px.append(prices)
    return np.array(close_px, dtype=dt)  # make the list of tuples into an array with dtype dt