3

我收到一个错误,我对以下脚本不太了解。我以为我可以快乐地将两个 numpy 数组倍增,但我不断收到此错误:

TypeError: unsupported operand type(s) for *: 'numpy.ndarray' and 'numpy.ndarray'

脚本如下:

def currents_to_resistance(Istack1, Istack2, A_list, x_list):

    #Error Calcs
    Videal_R1 = (1.380648e-23 * (27+273.15)) / (1.6021766e-19)
    print Videal_R1
    Istack1 = np.array(Istack1)
    Istack2 = np.array(Istack2)
    print Istack1
    print Istack2   

    g = Istack1*Istack2
    print g 

乘法前的打印 Istack1 Istack2 为

['0.0005789047' '0.0005743839' '0.0005699334' '0.000565551' '0.0005612346'
 '0.0005569839' '0.0005527969' '0.0005486719' '0.000544608' '0.0005406044'
 '0.0005366572' '0.000532768' '0.000528934' '0.0005251549' '0.0005214295'
 '0.0005177562' '0.0005141338' '0.0005105614' '0.000507039' '0.0005035643'
 '0.0005001368' '0.0004967555' '0.0004934193' '0.0004901279' '0.0004868796'
 '0.0004836736']
['0.000608027' '0.0006080265' '0.0006080267' '0.0006080267' '0.0006080261'
 '0.0006080261' '0.0006080262' '0.0006080261' '0.0006080263' '0.0006080272'
 '0.0006080262' '0.0006080262' '0.0006080257' '0.0006080256' '0.0006080258'
 '0.0006080256' '0.0006080252' '0.0006080247' '0.000608025' '0.0006080249'
 '0.000608025' '0.0006080251' '0.0006080249' '0.0006080254' '0.0006080251'
 '0.0006080247']

我调用函数使用

Re_list = currents_to_resistance(full_list[i][0],full_list[i][1], temp_A, temp_x)

我在这里想念什么?

4

2 回答 2

6

首先将字符串数组转换为浮点数组:

Istack1 = np.array(Istack1, np.float)
Istack2 = np.array(Istack2, np.float)
于 2012-05-08T03:55:58.850 回答
2

在我看来,那些ndarray字符串

>>> numpy.array(['1', '2', '3']) * numpy.array(['1', '2', '3'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'numpy.ndarray' and 'numpy.ndarray'

如果要将它们相乘,则需要将它们转换为floatss 或s:int

>>> numpy.array([1, 2, 3]) * numpy.array([1, 2, 3])
array([1, 4, 9])

一种方法可能是这样的。(但这取决于您传递给函数的内容。)

Istack1 = np.array(map(float, Istack1))

或者,使用列表推导:

Istack1 = np.array([float(i) for i in Istack1])

或者,从HYRY窃取(我忘记了明显的方法):

Istack1 = np.array(Istack1, dtype='f8')
于 2012-05-08T03:53:24.937 回答