【分享】Python科學(xué)計(jì)算備忘單

本資源由我翻譯,原文位于https://ipgp.github.io/scientific_python_cheat_sheet/,可以點(diǎn)擊此處下載原文高清圖打印學(xué)習(xí)和備查使用。

本人英文和術(shù)語理解有限,有些地方翻譯未必準(zhǔn)確,歡迎大家于下方留言,進(jìn)行解讀和更正。


目錄

純python

類型

a = 2           # 整數(shù)
b = 5.0         # 浮點(diǎn)數(shù)
c = 8.3e5       # 指數(shù)
d = 1.5 + 0.5j  # 浮點(diǎn)數(shù)
e = 4 > 5       # 布爾值
f = 'word'      # 字符串

列表

a = ['red', 'blue', 'green']       # 手動(dòng)初始化
b = list(range(5))                 # 通過迭代初始化
c = [nu**2 for nu in b]            # 列表推導(dǎo)式
d = [nu**2 for nu in b if nu < 3]  # 條件列表推導(dǎo)式
e = c[0]                           # 訪問元素
f = c[1:2]                         # 切片
g = c[-1]                          # 訪問最后一個(gè)元素
h = ['re', 'bl'] + ['gr']          # 列表粘連
i = ['re'] * 5                     # 重復(fù)列表
['re', 'bl'].index('re')           # 返回're'索引
a.append('yellow')                 # 添加新元素到列表尾部
a.extend(b)                        # 添加列表b的元素到a的尾部
a.insert(1, 'yellow')              # 插入元素到特定位置
're' in ['re', 'bl']               # 如果're'在列表中,返回true
'fi' not in ['re', 'bl']           # 如果'fi'不在列表中,返回true
sorted([3, 2, 1])                  # 返回排好序的列表
a.pop(2)                           # 移除和返回索引處的元素(默認(rèn)最后一個(gè))

字典

a = {'red': 'rouge', 'blue': 'bleu'}         # 字典
b = a['red']                                 # 翻譯(索引)條目
'red' in a                                   # 如果字典包含'red'鍵,返回true
c = [value for key, value in a.items()]      # 字典條目循環(huán)
d = a.get('yellow', 'no translation found')  # 返回默認(rèn)值
a.setdefault('extra', []).append('cyan')     # 使用默認(rèn)值初始化鍵
a.update({'green': 'vert', 'brown': 'brun'}) # 通過其他數(shù)據(jù)更新字典
a.keys()                                     # 獲取鍵的列表
a.values()                                   # 獲取值的列表
a.items()                                    # 獲取鍵值對列表
del a['red']                                 # 刪除鍵和相關(guān)聯(lián)的值
a.pop('blue')                                # 移除指定的鍵并返回對應(yīng)的值

集合

a = {1, 2, 3}                                # 手動(dòng)初始化
b = set(range(5))                            # 通過迭代初始化
a.add(13)                                    # 添加新元素到集合
a.discard(13)                                # 從集合中丟棄元素
a.update([21, 22, 23])                       # 從迭代變量中更新集合
a.pop()                                      # 移除和返回任意的集合元素
2 in {1, 2, 3}                               # 如果2在集合中,返回true
5 not in {1, 2, 3}                           # 如果5不在集合中,返回true
a.issubset(b)                                # 檢測是否a中每一個(gè)元素都在b里
a <= b                                       # issubset的操作符形式
a.issuperset(b)                              # 檢測是否b中的每個(gè)元素都在a里
a >= b                                       # issuperset的操作符形式
a.intersection(b)                            # 返回兩個(gè)集合的交集
a.difference(b)                              # 返回兩個(gè)或多個(gè)集合的差集
a - b                                        # difference的操作符形式
a.symmetric_difference(b)                    # 返回對稱差集
a.union(b)                                   # 返回并集
c = frozenset()                              # 不可變集合

字符串

a = 'red'                      # 賦值
char = a[2]                    # 獲取單個(gè)字符
'red ' + 'blue'                # 字符聯(lián)接
'1, 2, three'.split(',')       # 將字符分割為列表
'.'.join(['1', '2', 'three'])  # 將列表聯(lián)接為字符

操作符

a = 2             # 賦值
a += 1 (*=, /=)   # 改變和賦值
3 + 2             # 加法
3 / 2             # 整數(shù)(python2) 或者 浮點(diǎn)數(shù)(python3)除法
3 // 2            # 整除
3 * 2             # 乘法
3 ** 2            # 指數(shù)
3 % 2             # 求余
abs(a)            # 絕對值
1 == 1            # 相等
2 > 1             # 大于
2 < 1             # 小于
1 != 2            # 不等
1 != 2 and 2 < 3  # 邏輯與
1 != 2 or 2 < 3   # 邏輯或
not 1 == 2        # 邏輯非
'a' in b          # 檢測是否'a'在b中
a is b            # 檢測是否對象映射到相同的內(nèi)存(id)

控制流

# if/elif/else
a, b = 1, 2
if a + b == 3:
    print('True')
elif a + b == 1:
    print('False')
else:
    print('?')

# for
a = ['red', 'blue', 'green']
for color in a:
    print(color)

# while
number = 1
while number < 10:
    print(number)
    number += 1

# break
number = 1
while True:
    print(number)
    number += 1
    if number > 10:
        break

# continue
for i in range(20):
    if i % 2 == 0:
        continue
    print(i)

函數(shù)、類、生成器和修飾器

# 函數(shù)將代碼語句分類并返回一個(gè)派生值
def myfunc(a1, a2):
    return a1 + a2

x = myfunc(a1, a2)

# 類將屬性(數(shù)據(jù))和關(guān)聯(lián)的方法(函數(shù))進(jìn)行分類
class Point(object):
    def __init__(self, x):
        self.x = x
    def __call__(self):
        print(self.x)

x = Point(3)

# 生成器不用一次性創(chuàng)建所有值來進(jìn)行迭代
def firstn(n):
    num = 0
    while num < n:
        yield num
        num += 1

x = [i for i in firstn(10)]

# 修飾器可以用來修飾函數(shù)的行為
class myDecorator(object):
    def __init__(self, f):
        self.f = f
    def __call__(self):
        print("call")
        self.f()

@myDecorator
def my_funct():
    print('func')

my_funct()

IPython

控制臺(tái)

<object>?                   # 關(guān)于變量的信息
<object>.<TAB>              # tab補(bǔ)全

# 運(yùn)行腳本 / profile / debug
%run myscript.py

%timeit range(1000)         # 測量語句運(yùn)行時(shí)間
%run -t  myscript.py        # 測量腳本執(zhí)行時(shí)間

%prun <statement>           # 使用profiler執(zhí)行語句
%prun -s <key> <statement>  # 通過鍵排序,例如 "cumulative" or "calls"
%run -p  myfile.py          # profile腳本

%run -d myscript.py         # 以調(diào)試模式運(yùn)行腳本
%debug                      # 遇到意外后跳轉(zhuǎn)到調(diào)試器
%pdb                        # 遇到意外自動(dòng)運(yùn)行調(diào)試器

# 檢查歷史
%history
%history ~1/1-5  # 最后線程1-5行

# 運(yùn)行shell命令
!make  # 使用"!"前綴

# 清除命名空間
%reset

# 運(yùn)行剪貼板代碼
%paste

調(diào)試器

n               # 執(zhí)行下一行
b 42            # 在主文件42行設(shè)定斷點(diǎn)
b myfile.py:42  # 在'myfile.py'第42行設(shè)定斷點(diǎn)
c               # 繼續(xù)執(zhí)行
l               # 顯示代碼中當(dāng)前位置
p data          # 打印'data'變量
pp data         # 以美觀的方式打印'data'變量
s               # 步入子程序
a               # 打印函數(shù)收到的參數(shù)
pp locals()     # 顯示所有的局部變量
pp globals()    # 顯示所有的全局變量

命令行

ipython --pdb -- myscript.py argument1 --option1  # 遇到意外后進(jìn)入調(diào)試
ipython -i -- myscript.py argument1 --option1     # 完成后進(jìn)入控制臺(tái)

NumPy (import numpy as np)

數(shù)組初始化

np.array([2, 3, 4])             # 直接初始化
np.empty(20, dtype=np.float32)  # 大小為20的單精度數(shù)組
np.zeros(200)                   # 初始化200個(gè)0
np.ones((3,3), dtype=np.int32)  # 3 x 3的全1整數(shù)矩陣
np.eye(200)                     # 對角矩陣
np.zeros_like(a)                # 與a大小一樣的全0矩陣
np.linspace(0., 10., 100)       # 0到10,100個(gè)等分點(diǎn)
np.arange(0, 100, 2)            # 步長為2,從0到<100
np.logspace(-5, 2, 100)         # 從1e-5 -> 1e2的100個(gè)對數(shù)間隔值
np.copy(a)                      # 拷貝數(shù)組到新的內(nèi)存

索引

a = np.arange(100)          # 用0 - 99初始化
a[:3] = 0                   # 設(shè)置第一個(gè)到第3個(gè)為0
a[2:5] = 1                  # 設(shè)置索引2-4為0
a[:-3] = 2                  # 設(shè)置除了最后三個(gè)的其他所有值為2
a[start:stop:step]          # 索引/切片的通用形式
a[None, :]                  # 轉(zhuǎn)換為列向量
a[[1, 1, 3, 8]]             # 使用索引值返回?cái)?shù)組
a = a.reshape(10, 10)       # 轉(zhuǎn)換為10 x 10 矩陣
a.T                         # 返回矩陣的倒置
b = np.transpose(a, (1, 0)) # 調(diào)換矩陣到新的軸序
a[a < 2]                    # 返回元素對(向量)滿足條件的值

數(shù)組屬性和操作

a.shape                # 一個(gè)包含每個(gè)軸長度的元組
len(a)                 # 0軸的長度
a.ndim                 # 維度(axes)數(shù)目
a.sort(axis=1)         # 按軸對數(shù)組排序
a.flatten()            # 塌縮數(shù)組到1維
a.conj()               # 返回共軛復(fù)數(shù)
a.astype(np.int16)     # 投射為整數(shù)
a.tolist()             # 轉(zhuǎn)換(可能多維矩陣)為列表
np.argmax(a, axis=1)   # 返回給定軸次最大值的索引
np.cumsum(a)           # 返回累積和
np.any(a)              # 如果任意值為True,返回True
np.all(a)              # 如果所有值為True,返回True
np.argsort(a, axis=1)  # 返回按軸排序的索引數(shù)組
np.where(cond)         # 返回cond(條件)為True處的索引
np.where(cond, x, y)   # 返回滿足條件的元素

布爾數(shù)組

a < 2                         # 返回布爾值數(shù)組
(a < 2) & (b > 10)            # 元素對邏輯與
(a < 2) | (b > 10)            # 元素對邏輯或
~a                            # 邏輯矩陣的反(非)

元素對操作與數(shù)學(xué)函數(shù)

a * 5              # 用標(biāo)度乘
a + 5              # 用標(biāo)度加
a + b              # 與數(shù)組b相加
a / b              # 與數(shù)組b相除 (如果除以0,返回np.NaN)
np.exp(a)          # 指數(shù) (復(fù)數(shù)與實(shí)數(shù))
np.power(a, b)     # a的b次冪
np.sin(a)          # sine函數(shù)
np.cos(a)          # cosine函數(shù)
np.arctan2(a, b)   # arctan(a/b)函數(shù)
np.arcsin(a)       # arcsin函數(shù)
np.radians(a)      # 度到弧度
np.degrees(a)      # 弧度到度
np.var(a)          # 數(shù)組的方差
np.std(a, axis=1)  # 數(shù)組的標(biāo)準(zhǔn)差

內(nèi) 外積

np.dot(a, b)                  # 內(nèi)積: a_mi b_in
np.einsum('ij,kj->ik', a, b)  # 愛因斯坦求和約定
np.sum(a, axis=1)             # 軸1求和
np.abs(a)                     # 返回絕對值
a[None, :] + b[:, None]       # 外部和
a[None, :] * b[:, None]       # 外積
np.outer(a, b)                # 外積
np.sum(a * a.T)               # 矩陣標(biāo)準(zhǔn)化

線性代數(shù) 矩陣數(shù)學(xué)

evals, evecs = np.linalg.eig(a)      # 尋找特征值與特征向量
evals, evecs = np.linalg.eigh(a)     # 厄爾米特矩陣np.linalg.eig

讀 寫文件


np.loadtxt(fname/fobject, skiprows=2, delimiter=',')   # 讀ascii數(shù)據(jù)文件
np.savetxt(fname/fobject, array, fmt='%.5f')           # 寫ascii數(shù)據(jù)文件
np.fromfile(fname/fobject, dtype=np.float32, count=5)  # 讀二進(jìn)制數(shù)據(jù)文件
np.tofile(fname/fobject)                               # 寫二進(jìn)制數(shù)據(jù)文件
np.save(fname/fobject, array)                          # 保存為numpy 二進(jìn)制文件(.npy)
np.load(fname/fobject, mmap_mode='c')                  # 導(dǎo)入.npy文件

插值、積分與優(yōu)化

np.trapz(a, x=x, axis=1)  # 沿軸1積分
np.interp(x, xp, yp)      # 在x點(diǎn)的插值函數(shù)xp, yp
np.linalg.lstsq(a, b)     # 用最小二乘法求解a x = b

fft

np.fft.fft(a)                # a的復(fù)數(shù)傅里葉變換
f = np.fft.fftfreq(len(a))   # fft頻率
np.fft.fftshift(f)           # 將頻率0移到中間
np.fft.rfft(a)               # a的實(shí)數(shù)傅里葉變換
np.fft.rfftfreq(len(a))      # 實(shí)數(shù)傅里葉變換頻率

舍入

np.ceil(a)   # 向上取整
np.floor(a)  # 向下取整
np.round(a)  # 臨近取整

隨機(jī)變量

from np.random import normal, seed, rand, uniform, randint
normal(loc=0, scale=2, size=100)  # 100個(gè)正態(tài)分布數(shù)據(jù)點(diǎn)
seed(23032)                       # 設(shè)定種子數(shù)
rand(200)                         # [0, 1)區(qū)間200個(gè)隨機(jī)數(shù)
uniform(1, 30, 200)               # [1, 30) 200個(gè)隨機(jī)數(shù)
randint(1, 16, 300)               # [1, 16) 200個(gè)隨機(jī)整數(shù)

Matplotlib (import matplotlib.pyplot as plt)

圖形與軸

fig = plt.figure(figsize=(5, 2))  # 初始化圖
fig.savefig('out.png')            # 保存png圖像
fig, axes = plt.subplots(5, 2, figsize=(5, 5)) # 繪制子圖
ax = fig.add_subplot(3, 2, 2)     # 添加子圖到
ax = plt.subplot2grid((2, 2), (0, 0), colspan=2)  # 多個(gè)軸
ax = fig.add_axes([left, bottom, width, height])  # 添加自定義軸

圖像與軸屬性

fig.suptitle('title')            # 大的圖標(biāo)題
fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
                    hspace=0.5)  # 調(diào)整子圖位置
fig.tight_layout(pad=0.1, h_pad=0.5, w_pad=0.5,
                 rect=None)      # 調(diào)整子圖
ax.set_xlabel('xbla')            # 設(shè)置 xlabel
ax.set_ylabel('ybla')            # 設(shè)置 ylabel
ax.set_xlim(1, 2)                # 設(shè)置 x limits
ax.set_ylim(3, 4)                # 設(shè)置 y limits
ax.set_title('blabla')           # 設(shè)置軸標(biāo)題
ax.set(xlabel='bla')             # 一次性設(shè)置多個(gè)參數(shù)
ax.legend(loc='upper center')    # 激活圖例
ax.grid(True, which='both')      # 激活網(wǎng)格
bbox = ax.get_position()         # 返回軸邊界框
bbox.x0 + bbox.width             # 邊界框參數(shù)

繪制常規(guī)圖

ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # 線圖
ax.scatter(x,y, s=20, c=color)                  # 點(diǎn)圖
ax.pcolormesh(xx, yy, zz, shading='gouraud')    # fast colormesh
ax.colormesh(xx, yy, zz, norm=norm)             # slower colormesh
ax.contour(xx, yy, zz, cmap='jet')              # 彩線
ax.contourf(xx, yy, zz, vmin=2, vmax=4)         # 顏色填充
n, bins, patch = ax.hist(x, 50)                 # 直方圖
ax.imshow(matrix, origin='lower',
          extent=(x1, x2, y1, y2))              # 展示圖形
ax.specgram(y, FS=0.1, noverlap=128,
            scale='linear')                     # 繪制頻譜圖
ax.text(x, y, string, fontsize=12, color='m')   # 添加文字

Scipy (import scipy as sci)

插值

# 在索引位置插入數(shù)據(jù):
from scipy.ndimage import map_coordinates
pts_new = map_coordinates(data, float_indices, order=3)

# 簡單1維插值
from scipy.interpolate import interp1d
interpolator = interp1d(x, y, axis=2, fill_value=0., bounds_error=False)
y_new = interpolator(x_new)

積分

from scipy.integrate import quad     # python中的定積分
value = quad(func, low_lim, up_lim)  # 函數(shù)/方法

線性代數(shù)

from scipy import linalg
evals, evecs = linalg.eig(a)      # 尋找特征值和特征向量
evals, evecs = linalg.eigh(a)     # hermitian的求解函數(shù)
b = linalg.expm(a)                # 矩陣指數(shù)
c = linalg.logm(a)                # 矩陣對數(shù)

Pandas (import pandas as pd)

數(shù)據(jù)結(jié)構(gòu)

s = pd.Series(np.random.rand(1000), index=range(1000))  # 序列
index = pd.date_range("13/06/2016", periods=1000)       # 時(shí)間索引
df = pd.DataFrame(np.zeros((1000, 3)), index=index,
                    columns=["A", "B", "C"])            # DataFrame(數(shù)據(jù)框)

DataFrame

df = pd.read_csv("filename.csv")   # 讀和導(dǎo)入CSV文件到一個(gè)DataFrame
raw = df.values                    # 獲取DataFrame對象原始數(shù)據(jù)
cols = df.columns                  # 獲取列名的列表
df.dtype                           # 獲取所有列的數(shù)據(jù)類型
df.head(5)                         # 獲取頭5行
df.describe()                      # 獲取基本統(tǒng)計(jì)信息
df.index                           # 獲取列范圍索引

# 列切片
# (.loc[] 和 .ix[]都內(nèi)含所選擇的值)
df.col_name                         # 通過列名選擇列值作為序列
df[['col_name']]                    # 通過列名選擇列值作為DataFrame
df.loc[:, 'col_name']               # 通過列名選擇列值作為序列
df.loc[:, ['col_name']]             # 通過列名選擇列值作為DataFrame
df.iloc[:, 0]                       # 通過列索引選擇
df.iloc[:, [0]]                     # 通過列索引選擇,但不作為DataFrame 
df.ix[:, 'col_name']                # 用列名的混合方法
df.ix[:, 0]                         # 用列索引的混合方法

# 行切片
print(df[:2])                      # 打印dataframe前兩行
df.iloc[0:2, :]                    # 選擇dataframe的頭2行
df.loc[0:2,'col_name']             # 選擇dataframe的頭3行
df.loc[0:2, ['col_name1', 'col_name3', 'col_name6']]    # 選擇dataframe的頭3行與根據(jù)列名選擇3列
df.loc[0:2,0:2]                   # 選擇頭3行,頭3列
# 同樣,.loc[] 和 .ix[]都內(nèi)含所選擇的值

# Dicin
df[ df.col_name < 7 ]                            # 選擇符合col_name < 7的所有行
df[ (df.col_name1 < 7) & (df.col_name2 == 0) ]       # 用按位操作符結(jié)合多個(gè)邏輯條件
                                                     # 標(biāo)準(zhǔn)的Python布爾操作符不能在這里使用(and, or) cannot be used here. 
                                                     # 確保將每個(gè)條件封裝在括號(hào)中以使其工作。
df[df.recency < 7] = -100                        # 切片賦值
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容