matrix - 循环直到矩阵满?
问题描述
我有一个条件语句,它将矩阵 A 中的二进制值行添加到矩阵 B。我想把它放在一个循环中,以便它继续从矩阵 A 中添加行,直到矩阵 B 已满。目前,矩阵 B 被初始化为 10 x 10 的零矩阵。我是否需要以不同的方式初始化矩阵 B 才能创建此条件,还是有办法按原样进行?
下面大致是我的代码到目前为止的样子
from random import sample
import numpy as np
matrixA = np.random.randint(2, size=(10,10))
matrixB = np.zeros((10,10))
x, y = sample(range(1, 10), k=2)
if someCondition:
matrixB = np.append(matrixB, [matrixA[x]], axis=0)
else:
matrixB = np.append(matrixB, [matrixA[y]], axis=0)
解决方案
你不需要一个循环。使用智能索引真的很容易做到这一点。例如:
import numpy as np
A = np.random.randint(0, 10, size=(20,10))
B = np.empty((10, 10))
print(A)
# Copy till the row that satisfies your conditions. Here I assume it to be 10
B = A[:10, :]
print(B)
推荐阅读
- r - dplyr summarise 然后 summarise_at 在同一个管道中
- discord.py-rewrite - How can I mention whoever was mentioned in the command trigger?
- ios - iOS NSLocale.CurrentLocale.CountryCode 返回语言而不是国家代码
- c - 如何将列数据转换为行数据?
- javascript - 为 JavaScript 'if event.target' 使用类名
- r - 将时间的字符向量转换为 R 中的正确格式和 bin
- typescript - 在 TypeScript 中使用命名空间和 WebPack 时修复类不是构造函数错误
- xamarin - Xamarin 应用程序可以在 BrowserStack 上使用 App Live Local Testing
- wordpress - Woocommerce:检查购物车是否包含任何产品的功能
- python - Python else 语句的问题