用不同的数组替换元素 [英] replace element by element different arrays

查看:71
本文介绍了用不同的数组替换元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

a = np.array([1,2,3,4,5,6,7,8])

更方便的是,可以将数组重塑为a = np.array([[1,2,3,4],[5,6,7,8]]).

The array may be reshaped to a = np.array([[1,2,3,4],[5,6,7,8]]), whatever is more convenient.

现在,我有一个数组:

b = np.array([[11,22,33,44], [55,66,77,88]])

我想将a中的相应元素替换为每个元素.

I want to replace to each of these elements the corresponding elements from a.

a数组将始终包含与b一样多的元素.

The a array will always hold as many elements as b has.

因此,数组b将为:

[1,2,3,4], [5,6,7,8]

请注意,我必须将每个b子数组维数保持为(4,).我不想更改它,因此idx将使用0 to 3中的值.我想使a适合every four values.

Note, that I must keep each b subarray dimension to (4,). I don't want to change it.So, the idx will take values from 0 to 3.I want to make a fit to every four values.

我在重塑,分割,遮罩..etc等方面苦苦挣扎,我想不出办法.

I am struggling with reshape, split,mask ..etc and I can't figure a way to do it.

import numpy as np

#a = np.array([[1,2,3,4],[5,6,7,8]])
a = np.array([1,2,3,4,5,6,7,8])


b = np.array([[11,22,33,44], [55,66,77,88]])

for arr in b:
    for idx, x in enumerate(arr):
        replace every arr[idx] with corresponding a value

推荐答案

以下内容对我有用:

i = 0
for arr in b:
    for idx, x in enumerate(arr):
        arr[idx] = a[i]
        print(arr[idx])
        i += 1

输出(arr [idx]):1 2 3 4 5 6 7 8 如果键入print(b),它将输出[[1 2 3 4] [5 6 7 8]]

Output (arr[idx]): 1 2 3 4 5 6 7 8 If you type print(b) it'll output [[1 2 3 4] [5 6 7 8]]

这篇关于用不同的数组替换元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆