我有一个宽的二进制二维numpy数组,如下所示:

np_var:
0, 0, 1, 0, 1, ..., 0, 1
1, 0, 1, 0, 0, ..., 1, 0
...

每行有8个非零元素.我想用零快速替换每行中的第n个非零元素(最终每行有7个非零元素).

有没有一种简单的方法可以在没有循环的情况下快速执行此替换?

推荐答案

可以获取非零元素的索引,并使用它们替换数组中的值

arr = np.array(...)
print(arr)

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

nth_element = 5
non_zero_count = int(np.count_nonzero(arr) / len(arr)) # can be replaced by 8 if the size is fixed
indices = arr.nonzero()[1][nth_element - 1::non_zero_count]
arr[np.arange(len(arr)), indices] = 5
print(arr)

# [[1 1 1 0 0 1 0 5 1 0 0 1 1 0]
#  [0 1 1 1 1 0 5 0 0 1 1 0 1 0]
#  [1 0 1 1 0 1 5 1 0 1 0 0 1 0]
#  [0 1 1 0 1 0 0 1 5 1 1 0 1 0]
#  [1 1 1 0 0 1 5 0 0 1 1 0 0 1]
#  [0 0 1 1 1 1 5 0 1 1 0 0 1 0]
#  [1 0 1 0 1 0 1 5 1 0 0 1 0 1]
#  [1 0 1 1 1 0 5 1 0 0 1 0 1 0]
#  [0 0 1 1 1 1 0 5 0 1 1 0 0 1]
#  [0 1 1 1 0 0 0 1 5 0 1 1 1 0]]

Python相关问答推荐

PywinAuto在Windows 11上引发了Memory错误,但在Windows 10上未引发

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

C#使用程序从Python中执行Exec文件

将pandas Dataframe转换为3D numpy矩阵

SQLAlchemy Like ALL ORM analog

ThreadPoolExecutor和单个线程的超时

有没有一种ONE—LINER的方法给一个框架的每一行一个由整数和字符串组成的唯一id?

如何在Python中获取`Genericums`超级类型?

Python中的变量每次增加超过1

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

导入错误:无法导入名称';操作';

并行编程:同步进程

使用__json__的 pyramid 在客户端返回意外格式

不允许 Select 北极滚动?

如何在SQLAlchemy + Alembic中定义一个"Index()",在基表中的列上

Django抛出重复的键值违反唯一约束错误

仅取消堆叠最后三列

多索引数据帧到标准索引DF

如何在微调Whisper模型时更改数据集?

PyTorch变压器编码器中的填充掩码问题