我有1242个数字的名为a
的数组。我需要得到Python中所有数字的余弦值。在Python中计算数组的余弦值
当我使用:cos_ra = math.cos(a)
我得到一个错误,指出:
TypeError: only length-1 arrays can be converted to Python scalars
我该如何解决这个问题?
在此先感谢
我有1242个数字的名为a
的数组。我需要得到Python中所有数字的余弦值。在Python中计算数组的余弦值
当我使用:cos_ra = math.cos(a)
我得到一个错误,指出:
TypeError: only length-1 arrays can be converted to Python scalars
我该如何解决这个问题?
在此先感谢
问题是你使用numpy.math.cos
这里,它希望你传递一个标量。如果您想将cos
应用于迭代,请使用numpy.cos
。
In [30]: import numpy as np
In [31]: np.cos(np.array([1, 2, 3]))
Out[31]: array([ 0.54030231, -0.41614684, -0.9899925 ])
错误:
In [32]: np.math.cos(np.array([1, 2, 3]))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-8ce0f3c0df04> in <module>()
----> 1 np.math.cos(np.array([1, 2, 3]))
TypeError: only length-1 arrays can be converted to Python scalars
谢谢Ashwini Chaudhary,使用numpy工作! – ThePredator
因为我刚刚加入stackexachange,我的退缩只在11时 – ThePredator
@ user1469380 [接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235# 5235)并不需要任何声望;-),但upvoting答案确实。 –
我用numpy和它的工作 – ThePredator
使用numpy
:
In [178]: from numpy import *
In [179]: a=range(1242)
In [180]: b=np.cos(a)
In [181]: b
Out[181]:
array([ 1. , 0.54030231, -0.41614684, ..., 0.35068442,
-0.59855667, -0.99748752])
之外,numpy的数组操作都非常快:
In [182]: %timeit b=np.cos(a) #numpy is the fastest
10000 loops, best of 3: 165 us per loop
In [183]: %timeit cos_ra = [math.cos(i) for i in a]
1000 loops, best of 3: 225 us per loop
In [184]: %timeit map(math.cos, a)
10000 loops, best of 3: 173 us per loop
谢谢zhang,np工作 – ThePredator
@ user1469380 np;;) – zhangxaochen
math.cos()
只能在个别值调用,不是列表。
另一种选择,使用列表理解:
cos_ra = [math.cos(i) for i in a]
我用numpy,它的工作。谢谢 – ThePredator
不要使用'numpy.math.cos',使用'numpy.cos'。 –