开发者

Store NumPy Row and Column Headers

开发者 https://www.devze.com 2023-03-01 08:53 出处:网络
I have a numpy 2 dimensional numpy array that contains the daily stock prices for multiple stocks. For example

I have a numpy 2 dimensional numpy array that contains the daily stock prices for multiple stocks. For example

daily_prices = np.array([  
    [4,3,3,1],  
    [5,4,3,6],  
    [6,3,2,7],  
    [3,9,7,4],  
    [8,4,6,3],  
    [8,3,3,9]])  

where each row is a different date, and each column is a different stock.

I'd like to be able to store in array (or something more suitable), the names of the stocks going across (like 'MSFT', 'CSCO', 'GOOG', 'F') and the dates going down.

In other words, I wan开发者_运维百科t to name the rows and the columns like you would in a spreadsheet.

Is there a NumPythonic way to do this?


Use a structured array:

import numpy as np

daily_prices = np.array(
    [
        (4,3,3,1),
        (5,4,3,6),
        (6,3,2,7),
        (3,9,7,4),
        (8,4,6,3),
        (8,3,3,9)],
    dtype=[('MSFT','float'),('CSCO','float'),('GOOG','float'),('F','float') ]
    )

This allows you to access columns like this:

print(daily_prices['MSFT'])
# [ 4.  5.  6.  3.  8.  8.]

and rows like this:

print(daily_prices[2])
# (6.0, 3.0, 2.0, 7.0)
0

精彩评论

暂无评论...
验证码 换一张
取 消