user157522
user157522

Reputation: 371

Extracting a column from a matrix in python

I would like to extract the first column from a numpy matrix,

a = matrix
([[3, 2, 4, 6]
  [4, 5, 6, 5]
  [6, 4, 5, 3]
  [3, 5, 6, 7]])

and extract the first column as

a_column = [3,4,6,3]

I tried implementing extracting column from matrix however it did not work and gave the same matrix which I used as input as the output

Upvotes: 1

Views: 636

Answers (2)

will-hedges
will-hedges

Reputation: 1284

You can index the first item in each list with a comprehension. Also, use numpy to handle arrays.

import numpy as np

a = np.array([
  [3, 2, 4, 6]
  [4, 5, 6, 5]
  [6, 4, 5, 3]
  [3, 5, 6, 7]
])

column_a = [x[0] for x in a]

Upvotes: 0

Pramod Kumar
Pramod Kumar

Reputation: 1201

Numpy is the best library if you're dealing with matrices

import numpy as np
k = [[3, 2, 4, 6],
  [4, 5, 6, 5],
  [6, 4, 5, 3],
  [3, 5, 6, 7]]
k = np.array(k)
print(k[:,0])

Upvotes: 1

Related Questions