einverne
0
Q:

python slice an array

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array
Example:
>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> a[1:4]
[2, 3, 4]
15
# Basic syntax:
your_array[row, column] # To return specific element
your_array[row_start:row_end:row_step, col_start:col_end:col_step] # To 
# 	return slices of the array.

# Note, you need to import numpy as np to conveniently manipulate arrays
# Note, Python is 0-indexed
# Note, start is inclusive but stop is exclusive
# Note, the syntax for slicing arrays is the same as the syntax for 
# 	slicing lists except that you now have two dimensions to specify
# Note, to convert a numpy array to a list, use .tolist()

# Create array:
import numpy as np
your_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# This produces a 3x4 array (3 rows, 4 columns), which looks like:
	1	2	3	4
  	5	6	7	8
    9	10	11	12

# Example usage 1:
your_array[0,] # Return all columns of the 0th row
--> array([1, 2, 3, 4])
your_array[0,].tolist() # Convert np array to Python list
--> [1, 2, 3, 4]

# Example usage 2:
your_array[1, 3] # Return the element from row 1, column 3
--> 8

# Example usage 3:
your_array[1:3, 2:4] # Return rows 1-2 and cols 2-3
--> array([[ 7,  8],
           [11, 12]])

# Example usage 4:
your_array[:3:2, 1:5:2] # Return even rows (0, 2) and odd columns (1, 3)
--> array([[ 2,  4],
           [10, 12]])

# Example usage 5:
your_array[-1, 1:4] # Return columns 1-3 from the last row. 
--> array([10, 11, 12])
2

New to Communities?

Join the community