0

I've got a 2D matrix from numpy (np.zeros) and I would like that every element of this matrix is a 1D list with 2 elements, this is my code:

import numpy as np


N = 3
x = np.linspace(0,10,N)
y = np.linspace(0,10,N)

temp = np.zeros((N, N))

for i in range(len(x)):
    for j in range(len(y)):
        temp[i, j] = [x[i], y[j]]

but I've got error:

TypeError: float() argument must be a string or a real number, not 'list'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File (...), line 15, in <module>
    temp[i, j] = [x[i], y[j]]
ValueError: setting an array element with a sequence.

And okay, I understand this problem, but I don't know how to solve it.

  • 2
    You can also use a 3 dimensional matrix (not sure if this is what you wanted). `temp = np.zeros((N,N,2))` – NirF Feb 26 '23 at 17:16
  • 2
    Can you provide an example of your expected output? You have two arrays containing 6 entries between them - how would that be mapped into an array with 9 entries? – Brian61354270 Feb 26 '23 at 17:17
  • Related: [How to create a numpy array of lists?](https://stackoverflow.com/q/33983053/4518341) – wjandrea Feb 26 '23 at 17:18
  • 1
    It looks like you may be trying to re-invent [np.meshgrid](https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html) – Brian61354270 Feb 26 '23 at 17:20
  • 1
    What are you trying to solve? Do you want a 3d array of floats, or a 2d with actual list elements. Those are very different arrays. – hpaulj Feb 26 '23 at 17:22
  • @NirF that's work like I want, thanks everybody for help – Miłosz Wiśniewski Feb 26 '23 at 17:26
  • Not 100% clear what you're after, but I would try to avoid the loop if possible. Something like: `temp = np.stack(np.meshgrid(x, y)).transpose((2,1,0))` – Mark Feb 26 '23 at 17:34

2 Answers2

2

You can set the dtype=object when constructing the array and store lists, but that's quite inefficient. It's possible to define a custom dtype:

import numpy as np

# custom type of 2 float64 fields
pair_type = np.dtype("f8, f8")
x = np.zeros((3, 3), dtype=pair_type)
x[0, 0] = (1.5, 2.5)

You can retrieve x[i, j] as a tuple.

0

The result you are searching for can be conveniently achieved with numpy.meshgrid + numpy.stack:

np.stack(np.meshgrid(x, y, indexing='ij'), axis=-1)

array([[[ 0.,  0.],
        [ 0.,  5.],
        [ 0., 10.]],

       [[ 5.,  0.],
        [ 5.,  5.],
        [ 5., 10.]],

       [[10.,  0.],
        [10.,  5.],
        [10., 10.]]])
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105