Reputation: 505
I need to append 1D arrays (coordinates) into a 2d array using numpy
in python 3.6.
I can do this with lists using append, such as in the first example below.
mastlist =[]
i=0
for i in range (10):
i=i+1
coor = []
xcoor = i
ycoor =i*2
coor.append(xcoor)
coor.append(ycoor)
mastlist.append(coor)
print(mastlist)
But I want a more performant approach using numpy
arrays. When I attempt to convert the list approach to an array (second example),
import numpy as np
i=0
for i in range (10):
i=i+1
centroid =np.append(i,i*2)
masterarray=np.append([centroid],axis=0)
print(masterarray)
print(masterarray)
I get the error below.
My error is:
TypeError: append() missing 1 required positional argument: 'values'
I would of expected an array such as:
[[1, 2], [2, 4], [3, 6], [4, 8], [5, 10], [6, 12], [7, 14], [8, 16], [9, 18], [10, 20]]
I have also fumbled with attempts using extend
, vstack
, and concatenate
.
Any advice would be welcome.
Upvotes: 2
Views: 5382
Reputation: 651
I recommend you get single coordinate data firstly , then concatenate them. To my best knowledge, I dont think it can be done by np.append
The common method is np.concatenate, which I see it from cs231n class.
My sample codes are as follows:
import numpy as np
xcoor = np.arange(1,11,1).reshape(-1,1)
ycoor = np.arange(2,22,2).reshape(-1,1)
xycoor = np.concatenate((xcoor,ycoor),axis = 1)
print(xycoor)
Output:
[[ 1 2]
[ 2 4]
[ 3 6]
[ 4 8]
[ 5 10]
[ 6 12]
[ 7 14]
[ 8 16]
[ 9 18]
[10 20]]
Upvotes: 3
Reputation: 8903
Why not just use list comprehension?
import numpy as np
masterarray = np.array([[i,2*i] for i in range(1,11)])
output
array([[ 1, 2],
[ 2, 4],
[ 3, 6],
[ 4, 8],
[ 5, 10],
[ 6, 12],
[ 7, 14],
[ 8, 16],
[ 9, 18],
[10, 20]])
Upvotes: 1