Code:
import numpy as np
coordinates = np.array([])
for x in range(1, 9):
for y in range(1, 9):
coordinates = coordinates.insert(coordinates, (x,y))
Despite having read many tutorials and Stack Overflow responses, everything I try is not working. Can somebody help?
Replace this line:
coordinates = coordinates.insert(coordinates, (x,y))
With this:
coordinates = np.insert(coordinates, x,y)
You'll get an error because you started your loop at index 1, and 1 is the second position in Python (indexing starts at 0). You can't insert something at position 1 in an empty numpy
array. For your code to work, you have to start your loop at index 0:
import numpy as np
coordinates = np.array([])
for x in range(0, 9):
for y in range(0, 9):
coordinates = np.insert(coordinates, x, y)
Out[10]:
array([8., 8., 8., 8., 8., 8., 8., 8., 8., 7., 6., 5., 4., 3., 2., 1., 0.,
7., 6., 5., 4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0., 7.,
6., 5., 4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0., 7., 6.,
5., 4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0., 7., 6., 5.,
4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0.])
It isn't clear what you want to produce, but if you want a list of 'coordinate' tuples, here's one way:
In [310]: alist = []
...: for x in range(1,4):
...: for y in range(1,4):
...: alist.append((x,y))
...:
In [311]: alist
Out[311]: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
or as a list comprehension:
In [312]: [(x,y) for x in range(1,4) for y in range(1,4)]
Out[312]: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
Repeated calls to numpy
functions like np.insert
and np.append
is discouraged, since they create a whole new array each time. List append is much better - if you have to work repeatedly like this.
With numpy
use something like meshgrid
to generate the 'coordinates'
In [319]: np.meshgrid(range(1,4),range(1,4))
Out[319]:
[array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]), array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])]
In [320]: np.reshape(_,(-1,2)) # rearrange into (n,2) array
Out[320]:
array([[1, 2],
[3, 1],
[2, 3],
[1, 2],
[3, 1],
[1, 1],
[2, 2],
[2, 3],
[3, 3]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.