英文:
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'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.
</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("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.
答案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='ij'), axis=-1)
array([[[ 0., 0.],
[ 0., 5.],
[ 0., 10.]],
[[ 5., 0.],
[ 5., 5.],
[ 5., 10.]],
[[10., 0.],
[10., 5.],
[10., 10.]]])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论