study notes: Python Numpy

Cheryl
2 min readApr 5, 2020

Array — table of elements of same type (usually numbers)

  • rank: number of dim or array
  • shape: tuple of row by column of array
  • size: total number of elements in array

1.Creating numpy array

import numpy as np# Create array of rank 1
tmp = np.array([1, 2, 3])
# Create array of rank 2
tmp = np.array([[1, 2, 3], [4, 5, 6]])
# Create array from tuple
tmp = np.array((1, 2, 3))
# Create array of 0 of size 3 x 3
tmp = np.zeros((3, 3))
# Create array of constant value (or text)
tmp = np.full((3, 3), 4)
>> array([[4, 4, 4],
[4, 4, 4],
[4, 4, 4]])
# Create array of random values (between 0 - 1)
tmp = np.random.random((3,3))
# Create an array of sequence
tmp = np.arange(1,10,2) # range and step
tmp = np.arange(10) # starts from 0 and step not specified
tmp = np.linspace(0, 10, 5) # range and number of values

2.Accessing array using index

tmp = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
# Select first 2 rows and alternate columns 0 & 2
tmp1 = tmp[:2, ::2]
# Select specific elements
tmp2 = tmp[[1, 1, 3],
[0, 2, 1]]
>> array([5, 7, 14])# Selecting via conditions
tmp[tmp > 10]
>> array([11, 12, 13, 14, 15, 16])

3.Basic operations

# Adding and subtracting to an array
tmp - 1
# Sum all array elements
tmp.sum() #or
np.sum(tmp)
>> 136# Square each element
tmp**2
# Square root each element
np.sqrt(tmp)
# Adding arrays (need to have the same # col)
tmp3 = tmp[[1, 1, 0, 3],
[0, 2, 1, 3]]
>> array([ 5, 7, 2, 16])# tmp3 is added to every rowtmp + tmp3>> array([[ 6, 9, 5, 20],
[10, 13, 9, 24],
[14, 17, 13, 28],
[18, 21, 17, 32]])
# Transpose
tmp = np.array([[1, 2, 3],
[4, 5, 6]])
tmp.T
>> array([[1, 4],
[2, 5],
[3, 6]])
# Min/Max
tmp.max()
# Row wise Min/Max
tmp.max(axis=1)
# Column wise Min/Max
tmp.max(axis=0)

4.Datatype

# Check datatype
tmp.dtype
# Assign datatype
tmp = np.array([1, 2, 3], dtype=np.float64)

5.Split strings

# Split string (default split on space)
tmp = np.array('Breakfast at Tiffanys')
np.char.split(tmp)
# Split string using delimiter
tmp = np.array(‘Breakfast-at-Tiffanys')
np.char.split(tmp, sep=‘-')

--

--