Home > Blockchain >  Subsetting 2D NumPy Arrays
Subsetting 2D NumPy Arrays

Time:07-17

hello im on the path of learning the python and i am struggling to understand this problem can you please help me to solve this problem

Print out the 50th row of np_baseball. why the answer for this command is [49, :] From my perspective if the asking for the 50th it should be just [49] why there is additional :

Will be extremely glad for your respond

CodePudding user response:

The numpy doc on slicing states:

If the number of objects in the selection tuple is less than N, then : is assumed for any subsequent dimensions.

So both versions are actually the same.

The example the documentation gives, is this:

x = np.array([[[1],[2],[3]], [[4],[5],[6]]])
x[1:2]  # array([[[4],[5],[6]]])

CodePudding user response:

Looks like you are using this course:

https://github.com/datacamp/courses-introduction-to-python/blob/master/chapter4.md

and looking at this block of code:

# baseball is available as a regular list of lists

# Import numpy package
import numpy as np

# Create np_baseball (2 cols)
np_baseball = np.array(baseball)

# Print out the 50th row of np_baseball
print(np_baseball[49,:])

# Select the entire second column of np_baseball: np_weight_lb
np_weight_lb = np_baseball[:,1]

# Print out height of 124th player
print(np_baseball[123, 0])

Notice that the next line selecting a column uses the [:,1] notation:

np_baseball[:,1]

Here the ':' is required to identify/slice the first dimension, rows. In np_baseball[49,:], the ':' does the same thing, slicing the 2nd dimension. But as a shorthand, trailing dimensions don't need to be specified, so np_baseball[49] is fine.

When writing instructional answers I like to include the trailing slice even it isn't required by the code. I think it makes things clearer to (most :) ) human readers.

  • Related