用numpy中的数组填充数组?

时间:2015-05-20 13:32:49

标签: python arrays numpy

一个相当简单的问题,但我似乎找不到任何解决方案:

我正在尝试使用数组中两个数组的区别并将其作为新结果插入到新数组中...我希望代码澄清这个意图,即使它不起作用,因为python告诉我它不能将序列与数组计算结合起来...如何解决这个问题呢?提前谢谢!

MeteorNum = 5
#Coordinate Setup:

XPos = np.random.randint(0, 600, (MeteorNum,1))
YPos = np.random.randint(0, 800, (MeteorNum,1))

XYPos = np.hstack((XPos,YPos))
XYPos = np.vstack((XYPos, XYPos[0]))
print XYPos

#Distances:
r = np.zeros((MeteorNum,MeteorNum))

for i in range(0, MeteorNum):
    for x in range(0, MeteorNum):
        r[x,i] = (XYPos[x,:] - XYPos[i,:])
r = r*10**5
print r

这是我得到的错误:

runfile('C:/Users/Marco DS/Dropbox/1_TUDelft/4Q/AE1205 Python/python codes      2015/bonus assigments/week_5 Gravity simu.py', wdir='C:/Users/Marco   DS/Dropbox/1_TUDelft/4Q/AE1205 Python/python codes 2015/bonus assigments')
[[249 660]
 [256 605]
 [119 423]
 [422 398]
 [480 504]
 [249 660]]
Traceback (most recent call last):

  File "<ipython-input-57-4cd9cc29ece0>", line 1, in <module>
    runfile('C:/Users/Marco DS/Dropbox/1_TUDelft/4Q/AE1205 Python/python     codes 2015/bonus assigments/week_5 Gravity simu.py', wdir='C:/Users/Marco     DS/Dropbox/1_TUDelft/4Q/AE1205 Python/python codes 2015/bonus assigments')

  File "C:\Users\Marco DS\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)

File "C:\Users\Marco DS\Anaconda\lib\site-    packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/Marco DS/Dropbox/1_TUDelft/4Q/AE1205 Python/python codes 2015/bonus assigments/week_5 Gravity simu.py", line 37, in <module>
r[x,i] = (XYPos[x,:] - XYPos[i,:])

ValueError: setting an array element with a sequence.

2 个答案:

答案 0 :(得分:1)

尝试在容器数组中添加add_foreign_key :table, :column

dtype=

修改

  

dtype参数表示数组所需的数据类型,例如:   numpy.int8。默认为numpy.float64。

答案 1 :(得分:1)

要删除错误,我认为您需要在数组r中增加一个大小为2的维度:

r = np.zeros((MeteorNum,MeteorNum,2))

for for循环中的XYPos[x,:] - XYPos[i,:]形状为(2,)

这将返回一个形状为(5, 5, 2)的单个数组。