【发布时间】:2011-09-16 13:09:19
【问题描述】:
我是使用 numpy 类的新手,我在处理数组的内容时遇到了问题。代码如下:
# finance equation to apply to each element of array
for row in cum_ret:
for col in row:
if sum(row)!=0:
row[col] = prev_row[col]*(1+row[col])
else:
row[col] = 1
cum_ret[row][col] = row[col]
prev_row = row
# see changed contents
for row in cum_ret:
print row
现在我收到一条错误消息,指出使用的数组索引必须是整数或布尔类型。我明白了,因为“行”值也是一个数组,所以它不能索引一个数组对象。那么这样做的正确语法是什么,或者它们是我应该使用的方法?
提前致谢
cum_ret 数组是 float64s 的 2d ndarray,是我要修改的数组。 这是输出的简短 sn-p:
[[ 0. 0. 0. 0. 0. ]
[ 0.00046187 0.00836672 0.00020435 -0.00048292 0.00342209]
[-0.07633505 -0.00514199 -0.04133778 -0.02450642 -0.01865075]
...,
[ 0.01229435 0.00175341 0.00709808 0.00213371 0.0061171 ]
[-0.0118614 -0.00994933 -0.00557095 -0.00141945 -0.00347423]
[ 0.01214725 -0.00502466 0.00537611 -0.00035537 -0.00101685]]
这就是它正在发生的情况:
Traceback (most recent call last):
File "qstk1.py", line 37, in <module>
cum_ret[row][col] = row[col]
IndexError: arrays used as indices must be of integer (or boolean) type
【问题讨论】:
-
cum_ret的数据类型和形状是什么?错误究竟发生在哪里?堆栈跟踪是什么?
标签: python multidimensional-array numpy