Python在科學計算方面已經(jīng)有了廣泛的應用。其中有幾個常用的擴展非常實用,已經(jīng)成為了Python科學計算名副其實的代名詞。包括:
- NumPy: 快速數(shù)組處理
- SciPy: 數(shù)值運算
- matplotlib: 繪制圖表
- Pandas: 數(shù)據(jù)分析擴展
舉例
PI 的一種算法實現(xiàn)
pi = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 -...
import numpy as np
n = 10000
print np.sum(4.0 / np.r_(1:n:4, -3:-n:-4))
計算積分
from scipy.integrate import quad
print quad(lambda x : (1 - x ** 2) ** 0.5, -1, 1) * 2
作心形線
from matplotlib import pyplot as pl
x, y = np.mgrid[-2:2:500j, -2:2:500j]
z = (x ** 2 + y ** 2 -1) ** 3 - x ** 2 * y ** 3
pl.contourf(x, y, z, levels=[-1, 0], colors=['red'])
pl.gca().set_aspect("equal")
pl.show()
pandas數(shù)據(jù)處理
import pandas as pd
cols = 'id', 'age', 'sex', 'occupation', 'zip_code'
df = pd.read_csv('users.csv', delimiter='|', header=None, names=cols)
print df.head(5)
df.groupby('occupation').age.mean().order().plot(kind='bar', figsize=(12, 4))
待更新