[Python] Numpy manual

Numpy revise

Posted by Geng Zhan on 2017-12-11

from

ndarray


basic operation
1
2
3
4
5
6
7
8
9
10
11
12
from numpy import *
a = arange(15).reshape(3, 5)
b = array([[1,2,3], [2,3,4]])
a.shape # (3, 5)
a.size
a.max(axis=?)
a.mean(axis=?)
# use ravel to replace flatten
a.ravel()
a.T # transpose
a.astype(_) # _: np.float, np.int, np.uint8
a.dtype.name
creation

arange, random.rand, random.randint, linspace, ones, zeros, empty, logspace

slice
  • a[…, i]

    … represent unspecified dim

  • np.split(a, N)

    split a into evenly N parts

  • np.split(a, [])

    split a at certain index

concat
  • np.vstack(a, b)
  • np.hstack(a, b)
  • np.concatenate(a, b, axis = ?)
  • np.stack(a, b) Note: Stack in a new dimension
  • np.fliplr()
  • np.flipud()
basic math operation
  • np.dot

    Note: calculate dot product of two vectors

  • power

1
2
3
4
from numpy import *
a = ndarray
b = ndarray # same size as a
a ** b
random
1
2
3
4
5
6
7
8
import python.random as random

random.seed(CERTAIN_NUMBER)
random.random(SHAPE)
random.randint(LOWER, HIGHER, NUMBER)

b = random.permutation(a)
random.shuffle(a) # in-place
useful
  • operation on mask ndarray
1
2
3
4
5
a = np.arange(10)
a_g = a > 6
a_s = a < 7
a_g + a_s # or operand
a_g * a_s # and operand

Numpy Cheatsheet

Those two are copied from BHu by me and the origin of which are shown in the pics.

cheat_sheet


cheat_sheet_2