Programmieren mit PythonPakete
Many Python packages are available in every standard distribution of Python and can be used without having to worry about whether they're installed. These packages make up the standard library. To see a list of standard library packages, visit the standard library page of the Python documentation. Here's an example showing how to import the
math package and use the
sqrt function it contains:
import math math.sqrt(3)
Note that we access names like
sqrt provided by the package using the dot
math.sqrt. This is common practice, and it's a good idea because if functions are called in a way that makes it clear what package they came from, then (1) you can use the same name in multiple packages, and (2) you can easily identify which package that is supplying each function. We can also import individual functions and skip the dot syntax:
from math import sqrt sqrt(3)
Sometimes a package contains a subpackage which must itself be accessed with dot syntax:
from numpy.random import standard_normal standard_normal()
Scientific computing packages in Python
Here are some of the most important scientific computing packages (along with very brief code snippets to give you a sense of what calling the packages looks like in practice):
NumPy. Provides multi-dimensional arrays (like vectors, matrices, and higher-order arrays).
import numpy as np np.random.standard_normal((5,5)) # randomly fill a 5 × 5 matrix np.full((3,3),7) # make a 3 × 3 matrix full of 7's
Note that we import
numpy with the alias
np for brevity.
Pandas. Provides support for tabular data.
import pandas as pd iris = pd.read_csv("http://bit.ly/iris-dataset") iris
SciPy. Provides scientific computing tools for optimization, numerical integration, linear algebra, statistics, etc.
from scipy.optimize import minimize minimize(lambda x: x*(x-1), 1.0) # start from 1 and minimize x(x-1)
Matplotlib. Standard plotting package in Python. (Note: run the cell below twice to get the graph to display.)
import matplotlib.pyplot as plt import numpy as np plt.plot(np.cumsum(np.random.standard_normal(1000)))
SymPy. Pure math tools like symbolic integration/differentiation, number theory, etc.
from sympy import symbols, Eq, solve x = symbols("x") y = symbols("y") solve([Eq(x + 5*y, 2), Eq(-3*x + 6*y, 15)], [x, y])
The example above solves the system of equations:
for and .
To import just the
arcsin function from
numpy, we would use what statement?
from numpy import arcsin
sympy with alias
sp, we would use what statement?
import sympy as sp
To import the standard library package
itertools (with no alias), we would use what statement?