本文介绍了存储NumPy行和列标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy二维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.

我希望能够以阵列形式(或更合适的形式)存储所涉及的股票名称(例如"MSFT","CSCO","GOOG","F")和日期下来.

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.

有NumPythonic的方式可以做到这一点吗?

Is there a NumPythonic way to do this?

推荐答案

使用结构化数组:

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.]

以及类似的行:

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

这篇关于存储NumPy行和列标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:11