如何将数组中的每个元素变成另一个数组。

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

how to make each element in an array another array

问题

你好,我遇到一个问题。我有一个大小为(256,144)的NumPy数组。该数组中的每个元素都是0。现在我想将数组中的每个元素都设置为[0, 0, 0]。有没有办法可以做到这一点?

以下是代码部分,不需要翻译:

empty_windows = np.zeros((256, 144))
for i in range(256):
    for j in range(144):
        empty_windows[i, j] = [0, 0, 0]

这种方法不起作用,因为它会返回一个错误消息"ValueError: setting an array element with a sequence."

有没有办法可以实现这个目标?非常感谢。

英文:

Hi I came across a problem. I have a numpy array with size (256, 144). Each element is 0 in this array. Now I want to make each element in the array to be [0, 0, 0]. Is there a way of doing this?

The code is:

empty_windows = np.zeros(256, 144)
for i in range(256*144):
    empty_windows[i] = [0,0,0]

This method doesnt work as it returns an error message "ValueError: setting an array element with a sequence."

Is there a way of doing this? Thank you very much.

答案1

得分: 1

如果您不需要在empty_windows的大小为(256, 144)时执行任何操作,您可以简单地创建具有正确大小的数组:

empty_windows = np.zeros((256, 144, 3))
英文:

If you don't need to do anything with empty_windows while it has size (256, 144), you can simply create it with the proper size:

empty_windows = np.zeros((256, 144, 3))

答案2

得分: 0

你可以尝试创建一个具有所需形状的第二个numpy数组,这在你的情况下是(256,144,3),然后迭代它并根据需要修正元素。

empty_windows = np.zeros((256, 144))

x = np.random.rand(256, 144, 3)

for i in range(256):
  for j in range(144):
    x[i][j] = [empty_windows[i][j] for _ in range(3)]

empty_windows = x

你可能还希望重新熟悉一下numpy数组的使用,正如评论中提到的,特别是如何初始化和迭代它们。

英文:

You could try creating a second numpy array with the required shape, which in your case is (256,144,3) , iterating over it and correcting the elements as required.

empty_windows = np.zeros((256, 144))

x = np.random.rand(256,144,3)

for i in range(256):
  for j in range(144):
    x[i][j] = [empty_windows[i][j] for _ in range(3)]

empty_windows = x

You may also want to brush up on your understanding of numpy arrays, as the commenter mentioned, particularly how to initialize and iterate over them.

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

发表评论

匿名网友

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

确定