如何从矩阵中取列,并保持2D?

时间:2017-09-20 16:45:18

标签: python numpy matrix

我想从矩阵Cannot find module 'plugin-name' from "index.jS"

中选择i

enter image description here

我可以通过

来做到这一点
x

这是最好的方式吗?

3 个答案:

答案 0 :(得分:3)

不确定最佳方式这里有一些 -

x[:,[i]]
x[:, i, np.newaxis] # or use None in place of np.newaxis
np.atleast_2d(x[:,i]).T
x[:,i].reshape(-1,1)

现在,第一个是副本,因此不会是我想到的最佳方式,至少在内存效率方面考虑,这可能会影响性能效率。其他人只是输入数组的视图,因此应该更好。让我们验证一下 -

In [178]: x = np.random.rand(3,4)

In [180]: np.shares_memory(x, x[:,[2]] )
Out[180]: False

In [181]: np.shares_memory(x, x[:, 2, np.newaxis] )
Out[181]: True

In [182]: np.shares_memory(x, np.atleast_2d(x[:,2]).T )
Out[182]: True

In [199]: np.shares_memory(x,x[:,2].reshape(-1,1))
Out[199]: True

让我们在场上测试一下。让我们用另一个数组添加一个切片 -

In [200]: x = np.random.rand(10000000,10)

In [201]: i = 5

In [202]: a = np.random.rand(x.shape[0],1)

In [203]: %timeit a + x[:,[i]]
     ...: %timeit a + x[:, i, np.newaxis]
     ...: %timeit a + np.atleast_2d(x[:,i]).T
     ...: %timeit a + x[:,i].reshape(-1,1)
     ...: 
10 loops, best of 3: 97.6 ms per loop
10 loops, best of 3: 68.7 ms per loop
10 loops, best of 3: 68.5 ms per loop
10 loops, best of 3: 68.5 ms per loop

因此,验证前面讨论的想法。

答案 1 :(得分:2)

您可以通过以下方式解决问题:

x[:, [i]]

正如@Divakar所提到的,您也可以使用x[:, i, np.newaxis]np.atleast_2d(x[:,i]).T获得相同的结果。但是,最快的似乎是x [:,i,np.newaxis]:

In [1]: %timeit x[:, [1]]
11.6 µs ± 87.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [15]: %timeit x[:, 1, np.newaxis] # fastest
3.05 µs ± 108 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [16]: %timeit np.atleast_2d(x[:,1]).T
14.2 µs ± 113 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

答案 2 :(得分:1)

我通常使用长度为1的片段:

In [2]: x
Out[2]: 
array([[8, 7, 4, 5, 5],
       [3, 3, 3, 3, 6],
       [0, 7, 2, 5, 0],
       [0, 1, 6, 8, 5]])

In [3]: i = 3  # Which column to select.

In [4]: x[:, i:i+1]  # Use the slice i:i+1 to select the column.
Out[4]: 
array([[5],
       [3],
       [5],
       [8]])

这比x[:, i, np.newaxis]慢一点,可能是因为必须要评估表达式i+1