如何一次建立一列矩阵 [英] How to build a matrix one column at a time
问题描述
我想根据下面的代码一次建立一列矩阵,并使用现有矩阵中的列.
I am wanting to build some matrices one column at a time, with columns from an existing matrix, as per the code below.
# x is an existing matrix, y is an array, pos_classes is a set
for i in range(len(y)):
if y[i] in pos_classes:
x_pos = np.append(x_pos, x[i])
y_pos_actual = np.append(y_pos_actual, y[i])
else:
x_neg = np.append(x_neg, x[i])
y_neg_actual = np.append(y_neg_actual, y[i])
我的问题是,应如何初始化x_pos
和x_neg
,以便每个x[i]
都按列追加?我尝试如下,并且每个追加将x_pos
变成一维数组.
My question is, what should I initialise x_pos
and x_neg
as so that each x[i]
gets appended column-wise? I tried as below, and each append turns x_pos
into a 1D array.
x_pos = np.empty((0,x.shape[1]))
我对python还是很陌生,可能缺少明显的东西.
I'm fairly new to python and am probably missing something obvious.
推荐答案
您正在以错误的方式进行操作.在numpy中以矢量化的方式执行此类操作几乎总是更好.
You're going about this the wrong way. It's almost always better to do such things in a vectorized way in numpy.
首先,构建索引数组y_pos_actual
.然后,只需
First, build your index array y_pos_actual
. Then, simply do
x_pos = x[:, y_pos_actual]
这会将索引y_pos_actual
给定的所有列都选择到新的矩阵x_pos
中.您可以使用
This will select all columns given by the indices y_pos_actual
into a new matrix x_pos
. You can do the same row-wise using
x_pos = x[y_pos_actual, :]
这篇关于如何一次建立一列矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!