根据存储在另一个列表中的索引替换列表列表中的元素

时间:2018-05-27 11:49:18

标签: python numpy matrix indexing

我有以下数组:

example_array = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
indexes = [[1,2,3], [2,3], [0,4,2], [1,4,3], [0,4,3], [1,2,3], [1,2]]

我想根据索引中的索引将example_array中的元素替换为1。所以,预期的结果应该是:

example_array = [[0,1,1,1,0],[0,0,1,1,0],[1,0,1,0,1],[0,1,0,1,1],[1,0,0,1,1],[0,1,1,1,0],[0,1,1,0,0]].

我尝试了不同的方法,例如使用pandas,如下所示:

matrix = pd.DataFrame(example_array)

for row in matrix:
    for i in indexes:
        for j in i:
            x_u.iloc[x, j] = 1

但它并没有给我带来希望的结果!该解决方案不需要使用pandas库。 谢谢你的帮助!

6 个答案:

答案 0 :(得分:2)

你可以这样做:

example_array = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
indexes = [[1,2,3], [2,3], [0,4,2], [1,4,3], [0,4,3], [1,2,3], [1,2]]

for i,index in enumerate(indexes):
  for idx in index:
    example_array[i][idx] = 1
print example_array

输出:

[[0, 1, 1, 1, 0], [0, 0, 1, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 1], [1, 0, 0, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 0]]

答案 1 :(得分:1)

试试这个:

WHEN NOT MATCHED BY TARGET AND (source.BitCondition = 0) THEN
    INSERT INTO TargetTable

它还为您节省了嵌套循环!

答案 2 :(得分:1)

使用numpy数组,您可以直接将指定的索引设置为所需的值。

import numpy as np
example_array = np.array([[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])
indexes = [[1,2,3], [2,3], [0,4,2], [1,4,3], [0,4,3], [1,2,3], [1,2]]

for i, ind in enumerate(indexes):
    example_array[i, ind] = 1
print(a)

<强>输出

[[0 1 1 1 0]
 [0 0 1 1 0]
 [1 0 1 0 1]
 [0 1 0 1 1]
 [1 0 0 1 1]
 [0 1 1 1 0]
 [0 1 1 0 0]]

答案 3 :(得分:1)

example_array = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]];
indexes = [[1,2,3], [2,3], [0,4,2], [1,4,3], [0,4,3], [1,2,3], [1,2]];

for i in range(0, len(example_array)):
    for j in range(0, len(indexes[i])):
        example_array[i][indexes[i][j]] = 1;

print example_array;

答案 4 :(得分:1)

或者你可以使用理解:

result = [[1 if i in ind else e for i, e in enumerate(ea)] for ea, ind in zip(example_array, indexes)]

答案 5 :(得分:1)

有一个班轮:

indices = [[1, 2, 3], [2, 3], [0, 4, 2], [1, 4, 3], [0, 4, 3], [1, 2, 3], [1, 2]]
print([[1 if idx in sub else 0 for idx in range(5)] for sub in indices])

输出:

[[0, 1, 1, 1, 0], [0, 0, 1, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 1], [1, 0, 0, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 0]]