Python NumPy Tutorial for Absolute Beginners - #4 Array Slicing, Indexing & Looping

Published: 07 March 2021
on channel: Raza Zaidi
290
12

Learn programming in NumPy, a Python Library, 100 seconds at a time in this video for beginners. This is video number 4: NumPy Array Slicing, Indexing and looping.

I know im going fast in this video, please use timestamps below to navigate the video.
Timestamps:
00:00 -reshape an array
00:18 - flatten an array
00:26 - slicing an one dimensional array
00:44 - slicing a two dimensional array
00:59 - combine for loop with slicing




—————————————————————
NumPy Slicing, Indexing and Looping
—————————————————————
 
In the last video we covered that the shape function tells us how many rows and columns an array has.
With the reshape function we can rearrange all the values in a different amount of rows and columns
Here we changed the shape from 3 to 2 rows and from 4 columns to 6 columns
shape(3,4)
data.reshape(2,6)
 
to create a one dimensional array from a multi dimensional array we can use the function flatten.
 
Data.flatten()
 
to grab a piece of this data we can use slicing
slicing works in the same way for arrays as python lists
lets take a look at a one dimensional array and print the last three values
data = np.array([1,2,3,4])
print(data[1:3])
we can also print the last three values like this
print(data[-3:])
in a two dimensional array we need to pass two sets of indexes.
One set for the row and one set for the column
Data2 = np.array([[1,2,3,4],[1,2,3,4]])
Print(data2[0:1,0:1])
Another way to grab the first two rows and the first two columns is to write it like this
Print(data2[:2,:2])
 
all the basic statements covered in the intro to python series, like if statements and loops, can be used in combination with arrays.
So we can use the loop statement like this
data = np.array([1,2,3,4])
for numbers in data:
                print(numbers)
you can also loop through a slice of the array, by passing the index numbers between square brackets after data
for numbers in data[:2]:
                print(numbers)
and even combine it with an IF statement to check if a number occurs in the array.
If the number occurs, print a sentence with the number
If it doesn’t, the code just loops through the slice of the array
for numbers in data[:2]:
             If numbers == 2
print(“This is number “ + str(numbers))
Else:
continue
————————————————————————



🦁 Who are you?
My name is Raza. I am 30. I am an IT - manager right now, but I’ve been an accountant for the majority of my career.
I’m in love with #Python :)

You can find me here:
📷 Instagram:   / razacodes  
📈 Twitter:   / razacodes  
—————————————————————————————

Goals for 2021
Training Python hours: 55/1000
Python/Django Projects: 1/30
Subscribers: 1834/10,000

—————————————————————————————-
#100SecondsOfCode
#pythonforbeginners #programming