简体   繁体   English

根据Python中另一个数组中的索引创建一个数组

[英]Create an array according to index in another array in Python

I have an array like this: 我有一个像这样的数组:

X= [[1,2,3],
    [3,2,1],
    [2,1,3]]

Now I want to create another array Y. The elements in Y should take value 1 at positions where elements in X equal 2, otherwise they should take value 0. In this example, Y should equal to 现在,我要创建另一个数组Y。Y中的元素在X中的元素等于2的位置处应取值为1,否则它们应取值为0。在此示例中,Y应等于

Y=[[0,1,0],
   [0,1,0],
   [1,0,0]]

This would be greatly facilitated (and sped up) by using numpy : 使用numpy可以大大方便(并加快):

import numpy as np

Y = (np.array(X) == 2).astype(int)

>>> Y
array([[0, 1, 0],
       [0, 1, 0],
       [1, 0, 0]])

您可以像这样使用列表理解:

Y = [[int(i == 2) for i in l] for l in X]
Y = [[1 if i==2 else 0 for i in row] for row in X]

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

相关问题 根据另一个数组和索引数组创建一个numpy数组 - Create a numpy array according to another array along with indices array 根据另一个索引数组重复numpy数组元素 - Repeating numpy array elements according to another index array Python - 根据另一个数组中的大小对值进行排名 - Python - Ranking values according to size in an another array 使用另一个列表 python 从列表创建索引值数组 - Create array of index values from list with another list python 在 Python 中使用一个数组作为另一个数组的索引 - Use an array as the index of another array in Python 如何在 python 中根据另一个数组对列表进行排序以生成新数组 - How to sort a list according to another array to generate a new array in python 如何在Python中根据另一个数组中的值提取一个数组中的数据 - How to extract data in one array according to the values in another array in Python Python numpy 根据另一个数组排序数组并在轴上广播 - Python numpy sort array according to another array and broadcast over an axis 使用另一个数组的值作为索引填充一个数组。 如果索引重复,则根据并行数组确定优先级 - Fill an array using the values of another array as the indices. If an index is repeated, prioritize according to a parallel array 根据索引数组求和值 - Sum values according to an index array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM