Although there are several ways to do this, one of the easiest is to use the NumPy library. NumPy has many built-in commands to create arrays. For example:
np.array(List)
creates a NumPy array from a Python list. The size and shape of the array depend on the list entries. np.eye(N)
creates an NxN identity matrixnp.random.random((M,N))
creates an MxN matrix of random numbers between 0 and 1NumPy also includes many built-in commands to manipulate arrays in matrix-like ways. For example:
A+B
gives the element-wise sum of two arrays A
and B
A*B
gives the element-wise product of two arrays A
and B
A@B
gives the matrix product of two arrays A
and B
A.T
or np.transpose(A)
gives the transpose of the array A
There are many, many things you can do with NumPy arrays! These FAQs will give just a few examples that come up often in our work.
Two commands are helpful:
np.set_printoptions(suppress=True)
will supress the use of scientific notationnp.set_printoptions(precision=N)
will control the number N
of decimals to printimport numpy as np
A = np.exp(10*np.random.random((4,4)))
np.set_printoptions(suppress=False)
print('Using scientific notation:')
print(A)
print()
print('Suppressing scientific notation:')
np.set_printoptions(suppress=True)
print(A)
print()
print('Lowering the print precision:')
np.set_printoptions(precision=2)
print(A)
print()
Complete documentation on NumPy indexing can be found at the NumPy project page: https://numpy.org/doc/stable/user/basics.indexing.html.
Here we only give a few examples that we find useful. The examples here are for 1D arrays, but indexing works similarly for 2D (or 3D or 4D...) arrays, with commas separating the different dimensions. E.g. A[0,0]
corresponds to the zeroth row and zeroth column of the array A
, A[0,1]
corresponds to the zeroth row and 1th column, etc.
import numpy as np
# A contains numbers 0 through 9
A = np.arange(0, 10)
print('A:')
print(A)
print()
# This is a vector of length 10, i.e., shape is (10,).
# Note that (to NumPy) this is different from a matrix
# of dimension (10,1), i.e., a 10x1 matrix.
print('np.shape(A):')
print(np.shape(A))
print()
print('Backwards array:')
print(A[::-1])
print()
print('First element:')
print(A[0])
print()
print('Last element')
print(A[-1])
print()
print('Penultimate element:')
print(A[-2])
print()
print('Even elements')
print(A[0::2])
print()
print('Odd elements')
print(A[1::2])
print()
print('Every thid element')
print(A[0::3])
print()
print('First 4 elements:')
print(A[0:4])
print()
print('First 2 even elements:')
print(A[0:4:2])
print()
print('Odd elements backwards:')
print(A[::-2])
print()
Using the NumPy library, you can apply the @
symbol:
import numpy as np
A = np.array([[1, 2], [3,4]])
B = np.array([[5, 6], [7,8]])
print('A:')
print(A)
print()
print('B:')
print(B)
print()
print('A*B: ')
print(A*B)
print()
print('A@B: ')
print(A@B)
print()
print('B@A: ')
print(B@A)
print()
Use the np.linalg.inv()
command:
# Original matrix
A = np.array([[1, 2], [3,4]])
# Inverse
Ainv = np.linalg.inv(A)
print('Ainv:')
print(Ainv)
print()
# The product of the two should be (very nearly) the identity matrix
print('A@Ainv:')
print(A@Ainv)
Use the np.linalg.eig
or np.linalg.eigh
commands:
A = np.array([[-20, 50],[50, 10]])
evals, evecs = np.linalg.eigh(A)
print('A:')
print(A)
print()
print('Eigenvalues:')
print(evals)
print()
print('Eigenvectors:')
print(evecs)
print()
# evecs.T @ A @ evecs should be a diagonal matrix
# whose entries are the eigevectors corresponding
# to each eigenvalue:
print('Diagonalization:')
print(np.transpose(evecs)@A@evecs)
The easiest way to do this is probably using np.savetxt()
. The delimiter
flag can be used to indicate a customized string to separate the numeric data. (The default is a single white space.)
import numpy as np
dat = np.random.random((10,5))
print(dat)
np.savetxt('default.txt', dat)
np.savetxt('tabs.txt', dat, delimiter='\t')
np.savetxt('commas.txt', dat, delimiter=',')
np.savetxt()
?¶Use the optional fmt
flag. There are many options here, but as two most important examples:
fmt='%.5e'
. fmt='%.5f'
.
You can replace 5
here with however many decimal points you wish to preserve. import numpy as np
dat = np.random.random((10,5))
# One decimal point, no scientific notation:
np.savetxt('precision1.txt', dat, fmt='%.1f')
# Five decimal points, no scientific notation:
np.savetxt('precision5.txt', dat, fmt='%.5f')
# Five decimal points, with scientific notation:
np.savetxt('precision5sci.txt', dat, fmt='%.5e')
There are several ways to do this, but the easiest is probably np.loadtxt()
. Note that the text file must contain only numeric data, with the same number of data points in each line of the file (so that it can be loaded into a rectangular array).
import numpy as np
# Set print precision to 10 decimals
np.set_printoptions(precision=10)
dat = np.random.random((10,5))
print('Original data:')
print(dat)
print()
# Save the data with two different precisions:
np.savetxt('precision1.txt', dat, fmt='%.1f')
np.savetxt('precision5.txt', dat, fmt='%.5f')
dat1 = np.loadtxt('precision1.txt')
print('From 1-decimal precision file:')
print(dat1)
print()
# From 5-decimal precision file:
dat5 = np.loadtxt('precision5.txt')
print('From 5-decimal precision file:')
print(dat5)
print()
The syntax is the same as for tab-delimited data, but you must add the flag delimiter=','
.
import numpy as np
dat = np.random.random((10,5))
np.savetxt('precision5.txt', dat, fmt='%.5f', delimiter=',')
# From 5-decimal precision file:
dat5 = np.loadtxt('precision5.txt', delimiter=',')
print('From 5-decimal precision file:')
print(dat5)
print()