Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store NumPy Row and Column Headers

Tags:

python

numpy

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 want to name the rows and the columns like you would in a spreadsheet.

Is there a NumPythonic way to do this?

like image 386
Idr Avatar asked Apr 26 '11 19:04

Idr


Video Answer


1 Answers

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)
like image 109
unutbu Avatar answered Oct 17 '22 14:10

unutbu