Quick Python Numpy Tutorial : Creating and Slicing Array

This tutorial will show the very basics of a really useful Python library call Numpy.

Numpy is an open source project aimed to enable numerical computing with Python. The link above is to their website, I recommend going over there and checking them out, they have great documentation and tutorials that will help explain in depth how to use their library and how to install Numpy.

In this tutorial I will go over how to create simple arrays and how to select certain data from the array, know as slicing.

Creating Array

import numpy as np

#Creating array with 12 objects in it
a = np.arange(12)
print(a)
Output

0, 1 ,2, 3 ,4 ,5, 6 ,7 ,8 ,9, 10, 11

Array Shape

The dimensions of an array is called the shape of the array. The function reshape is used to convert the a array into a different shape.

# Creating 2-D Array 
c = a.reshape(2,6)
print("2-D Array",c)

#Creating 3-D Array
b = a.reshape((3, 4))
print("3-D Array",b)
Output

2-D Array [[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]

3-D Array [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]

Slicing Array Data

#Slice Array
#Select object from array
#Here the Third obj is chosen
x = a[3]
print(x)

Output

3

#Select 5-9
y = a[5:9]
print(y)

Output

5, 6, 7, 8

#Select the last column of each row
z = b[: ,3]
print(z)

Output

3 ,7 ,11

#Select the One and Second Row
#and the Last Column
z = b[:2 ,3]
print(z)

Output

3 ,7

Below is the entire source code for this tutorial

import numpy as np

#Creating array with 12 objects in it
a = np.arange(12)
print(a)

# Changing Shape of array
b = a.reshape((3, 4))
print("3-D Array",b)
c = a.reshape(2,6)
print("2-D Array",c)

#Slice Array
#Select object from array
#Here the Third obj is chosen
x = a[3]
print(x)

#Select 5-9
y = a[5:9]
print(y)

#Select the Last column of each row
z = b[: ,3]
print(z)

#Select the One and Second Row
#and the Last Column
z = b[:2 ,3]
print(z)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s