NUMPY:有没有更易读的方法来索引 numpy 数组?

问题描述

我有一个大约有 7 列的 Numpy 数组,我需要对某些值进行大量索引,但目前我这样做的方式并不容易阅读。例如。我想说 rates[-1][high] 或类似的话。我想也许我可以为例如创建变量。 high = 2 但我在许多不同的函数中使用相同的汇率数据,所以我必须在每个函数中设置这些变量或将它们作为参数传递,但这也不是很有用。有一个更好的方法吗?提前致谢!

if (
  rates[-1][4] > rates[-1][1]
  and rates[-2][4] > rates[-2][1]
  and rates[-1][4] > rates[-2][4]
):

解决方法

如果我正确理解了这个问题,您可以将“列”4 设置为它自己的数组。

import numpy as np
rates = rates = 1+.01*np.arange( 36 ).reshape( 4,9 )
rates
# array([[1.,1.01,1.02,1.03,1.04,1.05,1.06,1.07,1.08],#        [1.09,1.1,1.11,1.12,1.13,1.14,1.15,1.16,1.17],#        [1.18,1.19,1.2,1.21,1.22,1.23,1.24,1.25,1.26],#        [1.27,1.28,1.29,1.3,1.31,1.32,1.33,1.34,1.35]])

high = rates[:,4] 
high                                                                   
# array([1.04,1.31])

你的公式变成:

if (
  high[-1] > rates[-1][1]
  and high[-2] > rates[-2][1]
  and high[-1] > rates[-2][4] # or > high[-2]
):