This is an archived version of the course. Please see the latest version of the course.

Miscellaneous

A few extra NumPy tips that do not fit elsewhere!

Loading and saving arrays

You can save and load numpy arrays onto/from the disk.

The first option is to save them as binary files. There are actually Python pickle files.

  • *.npy files are usually for one array.
  • *.npz files are for multiple arrays.
a = np.array([1, 2, 3, 4, 5, 6])
np.save("myfile", a)
a_fromdisk = np.load("myfile.npy")
print(a_fromdisk)

b = np.array([[1,2],[3,4]])
np.savez("multiple", a=a, b=b)
c = np.load("multiple.npz")
print(c["a"])
print(c["b"])

The second option is to save them as text files.

np.savetxt("myfile.csv", a)
a_fromtext = np.loadtxt("myfile.csv")
print(a_fromtext)

Generating random numbers

To generate random numbers in NumPy, you should first import the Default Random Number Generator provided by NumPy.

from numpy.random import default_rng

You should then initialise the random number generator with a seed number (just choose any number).

Tip: Random numbers are not really random in computers. They are pseudo-random because you can reproduce the same ‘random’ sequence with a fixed seed number. This is important in your scientific experiments so that you can reproduce your experimental results!

seed = 7777
rg = default_rng(seed)

You can then use the random generator instance to generate random numbers or arrays.

x = rg.random((5,3))
print(x)
## [[0.94192575 0.59573376 0.58880255]
##  [0.71400906 0.24578678 0.63006854]
##  [0.26233112 0.39487634 0.65615324]
##  [0.85818932 0.20564809 0.9837931 ]
##  [0.18541645 0.67159972 0.99064663]]

# Generate random integers from 1 (inclusive) to 10 (exclusive)
y = rg.integers(1, 10, size=(5,3))  
print(y)
## [[9 8 7]
##  [7 2 8]
##  [9 9 4]
##  [1 9 6]
##  [6 3 3]]

Printing more values

NumPy only prints values at the start and end of the array if the array is too large.

print(np.arange(2000)) # [0 1 2 ... 1997 1998 1999]

To print more values, use set_printoptions()

np.set_printoptions(threshold=10000) # defualt threshold is 1000
print(np.arange(2000))  # should print all numbers now