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.

7
  • 2
    You can also use a 3 dimensional matrix (not sure if this is what you wanted). temp = np.zeros((N,N,2)) Commented Feb 26, 2023 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? Commented Feb 26, 2023 at 17:17
  • Related: How to create a numpy array of lists? Commented Feb 26, 2023 at 17:18
  • 1
    It looks like you may be trying to re-invent np.meshgrid Commented Feb 26, 2023 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. Commented Feb 26, 2023 at 17:22

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.]]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.