OKPEDIA PYTHON MATRIX

Extracting a Column from a Python Matrix

Extracting a column from a matrix, previously set up with numpy's array() function, involves either iterating over the rows or transposing the matrix itself.

Example:

m=array([[1,2,3],[4,5,6],[7,8,9]])

This line of code represents a 3x3 matrix, consisting of 3 rows and 3 columns.

the example matrix

Now, let's focus on how to efficiently extract the first column using Python.

Here are a couple of effective strategies:

Strategy 1: Transposing the Matrix

One straightforward method is to transpose the matrix:

m.T

This command rearranges the matrix columns into neat lists, essentially flipping the matrix from rows to columns.

array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])

To access the first column, simply select the first row from the transposed matrix.

The index for the first column is 0.

m.T[0]

This returns the elements of the matrix's first column, neatly packaged.

array([1, 4, 7])

Effectively, this is the first column from our original matrix, m.

the first column of the matrix

Strategy 2: Iterating Through Rows

Alternatively, you can select any column by iterating through the matrix's rows and picking out the elements of the desired column.

For example, this line loops through all rows in matrix m, extracting the second element from each with row[1].

[row[1] for row in m]

The output looks like this:

[2, 5, 8]

And just like that, you've got the second column from the starting matrix.

the second column of the matrix

To retrieve the third column, you would use row[2], and for the first, row[0].

Note: Extracting a single column requires reading through each row in the matrix.

https://how.okpedia.org/en/python/how-to-extract-matrix-column-in-python


Report us an error or send a suggestion to improve this page


Matrix in Python


FacebookTwitterLinkedinLinkedin