Convert row vector to column vector in NumPy

前端 未结 2 805
野的像风
野的像风 2020-12-03 05:15
import numpy as np

matrix1 = np.array([[1,2,3],[4,5,6]])
vector1 = matrix1[:,0] # This should have shape (2,1) but actually has (2,)
matrix2 = np.array([[2,3],[5,6]         


        
相关标签:
2条回答
  • 2020-12-03 05:53

    The easier way is

    vector1 = matrix1[:,0:1]
    

    For the reason, let me refer you to another answer of mine:

    When you write something like a[4], that's accessing the fifth element of the array, not giving you a view of some section of the original array. So for instance, if a is an array of numbers, then a[4] will be just a number. If a is a two-dimensional array, i.e. effectively an array of arrays, then a[4] would be a one-dimensional array. Basically, the operation of accessing an array element returns something with a dimensionality of one less than the original array.

    0 讨论(0)
  • 2020-12-03 05:55

    Here are three other options:

    1. You can tidy up your solution a bit by allowing the row dimension of the vector to be set implicitly:

      np.hstack((vector1.reshape(-1, 1), matrix2))
      
    2. You can index with np.newaxis (or equivalently, None) to insert a new axis of size 1:

      np.hstack((vector1[:, np.newaxis], matrix2))
      np.hstack((vector1[:, None], matrix2))
      
    3. You can use np.matrix, for which indexing a column with an integer always returns a column vector:

      matrix1 = np.matrix([[1, 2, 3],[4, 5, 6]])
      vector1 = matrix1[:, 0]
      matrix2 = np.matrix([[2, 3], [5, 6]])
      np.hstack((vector1, matrix2))
      
    0 讨论(0)
提交回复
热议问题