如何向大numy矩阵添加列

2024-04-19 02:07:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我碰巧有一个2-DNumPy数组,形式如下:

2 3
1 2
3 9 
.
.
.

我需要向其中添加另一列,以便它表示前两列的squared sum,如:

2 3 13
1 2 5
3 9 36
. 
.
.

我应该使用什么NumPy函数来添加第三列?我的数组有大量的行,我不想使用for循环。你知道吗


Tags: 函数numpyfor数组形式sumsquareddnumpy
3条回答

首先计算平方和,然后使用numpy.column_stack将其与原始数组绑定:

a = np.array([[2,3], [1,2], [3,9]])

np.column_stack((a, np.sum(np.power(a, 2), axis=1)))
#array([[ 2,  3, 13],
#       [ 1,  2,  5],
#       [ 3,  9, 90]])
In [273]: x=np.array([[2,3],[1,2],[3,9]])
In [274]: x**2
Out[274]: 
array([[ 4,  9],
       [ 1,  4],
       [ 9, 81]], dtype=int32)

keepdims执行求和,同时保留2d形状

In [275]: (x**2).sum(axis=1, keepdims=True)
Out[275]: 
array([[13],
       [ 5],
       [90]], dtype=int32)

然后可以直接串联:

In [276]: np.concatenate((x,_),axis=1)
Out[276]: 
array([[ 2,  3, 13],
       [ 1,  2,  5],
       [ 3,  9, 90]])

reshapehstackcolumn_stack做同样的事情,只是创建用于连接的列数组的方法不同。你知道吗

它只是简单的,切片第一列和第二列,找到平方和,并连接到它原来的numpy矩阵。你知道吗

就一行。你知道吗

       np.concatenate((x,np.array([x[:,0]**2 + x[:,-1]**2]).T),axis=1)

相关问题 更多 >