简体   繁体   English

Python:根据某些条件从另一个一维数组替换二维数组中的值

[英]Python: replace values in a 2d array from another 1d array based on some conditions

thanks in advance for your help!在此先感谢您的帮助! I would like to the do the following, but I am new to Python, kind of unsure what to do efficiently.我想做以下事情,但我是 Python 新手,有点不确定如何有效地做。

  1. I have a 2d array, for example A=[[1,1],[2,3]] .我有一个二维数组,例如A=[[1,1],[2,3]]
  2. Each value in the above 2d array corresponds to the index in another 1d array, for example: B=[0.1,0.2,0.8,0.9] .上述二维数组中的每个值对应另一个一维数组中的索引,例如: B=[0.1,0.2,0.8,0.9]
  3. The end result should be like: C=[[0.2,0.2],[0.8,0.9]] .最终结果应该是: C=[[0.2,0.2],[0.8,0.9]] That means, C[i,j]=B[index=A[i,j]] .这意味着, C[i,j]=B[index=A[i,j]]

The above is a simple example.上面是一个简单的例子。 But in practice, A can be a huge array, so I would really appreciate if there is any way to do this efficiently.但在实践中,A 可能是一个巨大的数组,所以如果有任何方法可以有效地做到这一点,我将不胜感激。 Thank you!谢谢!

According to your post, you already almost got the answer.根据您的帖子,您几乎已经得到了答案。 If you are really looking for a one line code, you can do this.如果您真的在寻找单行代码,您可以这样做。

c = B[A]

c
Out[24]: 
array([[0.2, 0.2],
       [0.8, 0.9]])

The code above is for numpy array.上面的代码用于 numpy 数组。 On the other hand, if it is a list, list comprehension would be required.另一方面,如果它是一个列表,则需要列表理解。

First try planning the sequence from index of first list and the relation with the result list.首先尝试从第一个列表的索引和与结果列表的关系规划序列。

A = [[1,1],[2,3]]
B=[0.1,0.2,0.8,0.9]

C = [[B[i] for i in j] for j in A]

print(C)

Based on your comments on answer by @PAUL ANDY DE LA CRUZ YANAC, I see that you are trying to use numpy and avoid for loop but as far as my knowledge, you need to use a for loop at least once.根据您对@PAUL ANDY DE LA CRUZ YANAC 回答的评论,我看到您正在尝试使用numpy并避免for loop ,但据我所知,您需要至少使用一次for loop

import numpy as np

for x, y in np.ndindex(np.array(A).shape):
    A[x][y] = B[A[x][y]]

Note: This approach changes the original list A .注意:此方法更改了原始列表A But if you want to create a new list, look at the solution by @Paul Dlc.但是,如果您想创建一个新列表,请查看@Paul Dlc 的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM