如何从数组中手动​​选择值 [英] How to manually select values from an array

查看:34
本文介绍了如何从数组中手动​​选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个矩阵数组

For example I have a matrix array

a=np.arrange(25).shape(5,5)
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

如何制作要手动选择的一维元素数组?例如[2,3],[4,1],[1,0]和[2,2],因此我得到以下信息:

How do I make an 1D array of elements that I would like to choose manually? For example [2,3], [4,1], [1,0] and [2,2], so I get the following:

b=[13, 21, 5, 12]

该数组应该是引用,而不是副本.

The array should a reference rather than a copy.

推荐答案

您可以为此创建函数.

# defining the function
def get_value(matrix, row_list, col_list):
    for i, j in zip(row_list, col_list):
        return matrix[row_list, col_list]

# initializing the array
a = np.arange(0, 25, 1).reshape(5, 5)

# getting the required values and printing
b = get_value(a, [2,4,1,0], [3,1,0,2])

# output
print(b)

修改

我将原样保留先前的答案,以防万一其他人偶然发现并需要它.

I'll let the previous answer be as is, just in case if anyone else stumbles upon that and needs it.

问题所要提供的是 b 中的值(即 b [0] 13 ),然后将其更改为原始矩阵 a 基于 a b 传递的值的索引.

What the question wants is to give a value from b (i.e. b[0] which is 13) and change the value from the original matrix a based on the index of that passed value from b in a.

def change_the_value(old_mat, val_to_change, new_val):
    mat_coor = np.array(np.matrix(np.where(old_mat == val_to_change)).T)[0]
    old_mat[mat_coor[0], mat_coor[1]] = new_val
 
a = np.arange(0, 25, 1).reshape(5,5)
b = [13, 16, 5, 12]

change_the_value(a, b[0], 0)

这篇关于如何从数组中手动​​选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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