Q:

python how to slice arrays

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
#slicing arrays:
#generic sampling is done by 
#arr[start:end] -> where start is the starting index and end is ending idx
>>> import numpy as np
>>> arr = np.array([1,2,3,4,5])
>>> print(arr[1:5]) #starting idx 1 to ending index 4
[2 3 4 5]#it will print from starting idx to ending idx-1

#if you leave the ending index blank it will print all 
#from the starting index till end
>>> arr = np.array([2,6,1,7,5])
>>> print(arr[3:])
[7 5]
>>> print(arr[:3]) #if you leave the starting index blank it will print from 0 index to the ending idx-1\
[2 6 1]
>>> print(arr[:])
[2 6 1 7 5]
#leaving both the index open will print the entire array.

##########STEP slicing########
#if you want to traverse by taking steps more than 1 
#we use step slicing in that case
#syntax for step slicing is : arr[start:end:step]
>>> arr = np.array([2,6,1,7,5,10,43,21,100,29])
>>> print(arr[1:8:2])#we have taken steps of two
[ 6  7 10 21]


 
  
 
1
>>> a[1:4]
[2, 3, 4]
2

New to Communities?

Join the community