How to access a NumPy array by column

How to access a NumPy array by column

To access a NumPy array by column, you use array indexing. Remember, a NumPy array uses a 0-based index system.

Here's a step-by-step guide:

  • First, ensure you have NumPy imported:
import numpy as np 
  • Create a sample 2D array:
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(array) 

This will give:

[[1 2 3] [4 5 6] [7 8 9]] 
  • Access by column:

To access the first column:

first_column = array[:, 0] print(first_column) 

Output:

[1 4 7] 

For the second column:

second_column = array[:, 1] print(second_column) 

Output:

[2 5 8] 

And so on...

In general, to access the nth column, you would use:

nth_column = array[:, n-1] 

The : symbol means you're taking all rows for the specified column index.


More Tags

autoplay fastlane user-interface datacontext android-linearlayout asp.net-core-webapi kotlin android-location listitem sax

More Programming Guides

Other Guides

More Programming Examples