在Python的NumPy中,将列表作为二维数组的元素。

huangapple go评论61阅读模式
英文:

Put a list as element in 2D array in Python numpy

问题

我从numpy得到了一个2D矩阵np.zeros),我希望这个矩阵的每个元素都是一个具有2个元素的1D列表这是我的代码

```python
import numpy as np

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

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

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

但是我得到了错误:

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

上述异常直接导致了以下异常

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.

我理解了这个问题,但是不知道如何解决它。


<details>
<summary>英文:</summary>

I&#39;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&#39;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&#39;t know how to solve it.

</details>


# 答案1
**得分**: 2

你可以在构建数组时设置`dtype=object`并存储列表,但这样效率较低。也可以定义自定义的dtype:

```python
import numpy as np

# 定义包含两个float64字段的自定义类型
pair_type = np.dtype("f8, f8")
x = np.zeros((3, 3), dtype=pair_type)
x[0, 0] = (1.5, 2.5)

你可以将x[i, j]检索为一个元组。

英文:

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(&quot;f8, f8&quot;)
x = np.zeros((3, 3), dtype=pair_type)
x[0, 0] = (1.5, 2.5)

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

答案2

得分: 0

以下是翻译好的部分:

使用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.]]])
英文:

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

np.stack(np.meshgrid(x, y, indexing=&#39;ij&#39;), axis=-1)

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

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

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

huangapple
  • 本文由 发表于 2023年2月27日 01:12:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573682.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定