Adam Merckx
Adam Merckx

Reputation: 1214

How could I append a coordinate value to an array of coordinates?

I am trying to append a coordinate to an array of coordinates.

But I am getting this:

 [array([637, 257]), array([[114, 233], [114, 163]])]

Instead of:

[[637, 257], [114, 233], [114, 163]]

I am using np.append to append the single coordinate to the array of coordinates. What am I missing here?

import numpy as np 
coord = [(637, 257)]
coordinates = np.genfromtxt('Coordinates.csv', dtype =int, delimiter = ",")
coord.append(coordinates)
print(coord)

Upvotes: 3

Views: 3485

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

Well by appending, you add a single element to the list. But the coordinates are a 2d array (an array where each row is a coordinate, so an n× 2 array).

You can use .extend(..) or += to add an iterable of elements (the rows):

import numpy as np 
coord = [(637, 257)]
coordinates = np.genfromtxt('Coordinates.csv', dtype =int, delimiter = ",")
coord += coordinates
print(coord)

Now we get a list containing three elements: one 2-list, and 2 arrays. In case you want to convert the coordinates to lists as well, we can perform a mapping:

import numpy as np 
coord = [(637, 257)]
coordinates = np.genfromtxt('Coordinates.csv', dtype =int, delimiter = ",")
coord += map(list, coordinates)
print(coord)

Upvotes: 2

blue note
blue note

Reputation: 29071

You need to use coord.extend(coordinates) instead of append. Append just adds the whole list as a single element, while extend concatenates the new list to the old one.

Upvotes: 4

Related Questions