Python 无法按名称从numpy数组中获取值

Python 无法按名称从numpy数组中获取值,python,arrays,numpy,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 = [] fo

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

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

关于最佳方法有什么建议吗?

正如评论所说,您似乎在数组列表中添加一个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
数据['sym']将索引字典中键为'sym'的条目。您拥有的数据结构是一个列表。使用data.indexget_pxing可能会返回数组close_px的列表,而不是numpy数组。