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

标签 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中的元素根据indexes中的索引替换为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 库。 感谢您的帮助!

最佳答案

你可以这样做:

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]]

关于python - 根据存储在另一个列表中的索引替换列表列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50551827/

相关文章:

python - 使用 holoviews/hvplot 创建绘图网格并设置最大列数

python - Scipy odeint 非负解

python - numpy `arange` 超过最终值

python - VS Code Python 调试器无法连接到正在运行的进程(超时)

python - 从 C 结构创建 PyBuffer

java - 在 Java 中替换矩阵中的零

在 C 中将数据从一个矩阵复制到另一个矩阵

matlab - 初始化 3D 矩阵并添加新数据

python - Python 3 中字符串函数的意外输出

python - Numpy reshape 对复制数组和未复制数组的作用不同