简体   繁体   中英

Python 2D numpy.ndarray slicing without comma

Recently someone told me to extract the first two columns of a 2D numpy.ndarray by

firstTwoCols = some2dMatrix[:2]

Where is this notation from and how does it work?

I'm only familiar with the comma separated slicing like

twoCols = some2dMatrix[:,:2]

The : before the comma says to get all rows, and the :2 after the comma says for columns 0 up to but not including 2.

firstTwoCols = some2dMatrix[:2]

This will just extract the first 2 rows with all the columns.

twoCols = some2dMatrix[:,:2] is the one that will extract your first 2 columns for all the rows.

The syntax you describe does not extract the first two columns; it extracts the first two rows. If you specify less slices than the dimension of the array, NumPy treats this as equivalent to all further slices being : , so

arr[:2]

is equivalent to

arr[:2, :]

for a 2D array.

Not sure I understand the question but...

If you do:

>>> Matrix = [[x for x in range(1,5)] for x in range(5)] 
>>> Matrix
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

doing Matrix[:2] , it will select the first two list in Matrix , [1, 2, 3, 4], [1, 2, 3, 4] . But if you do:

>>> Matrix[:,:2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple

But if you work with a Numpy, do:

Matrix = np.array(Matrix)

>>>Matrix[:, :2]
array([[1, 2],
       [1, 2],
       [1, 2],
       [1, 2],
       [1, 2]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM