版權聲明:License CC BY-NC-SA 4.0 https://blog.csdn.net/wizardforcel/article/details/73252039
# 來源:NumPy Cookbook 2e Ch11
np.random.seed(44)
a = np.random.random_integers(-4, 4, 7)
print(a)
# [ 0 -1 -3 -1 -4 0 -1]
# ufunc 的 at 方法可以對數組元素部分調用
np.sign.at(a, [2, 4])
print(a)
# np.sign.at(a, [2, 4]) print(a)
np.random.seed(20)
a = np.random.random_integers(0, 7, 9)
print(a)
# [3 2 7 7 4 2 1 4 3]
# partition 僅僅排序所選位置
# 也就是說 a 中下标為 4 的元素在排序後的位置
# 其它的不保證
print(np.partition(a, 4))
# [2 3 1 2 3 7 7 4 4]
np.random.seed(46)
a = np.random.randn(30)
estimates = np.zeros((len(a), 3))
# nanmean nanvar 和 nanstd 可以用于計算
# 排除 NaN 值的均值、方差和标準差
for i in xrange(len(a)):
# 依次把 a[i] 設為 NaN
# 計算均值、方差和标準差
b = a.copy()
b[i] = np.nan
estimates[i,] = [np.nanmean(b), np.nanvar(b), np.nanstd(b)]
print("Estimator variance", estimates.var(axis=0))
# Estimator variance [ 0.00079905 0.00090129 0.00034604]
# full 建立純量數組
# full(size, val) 等價于 ones(size) * val
print(np.full((1, 2), 7))
# array([[ 7., 7.]])
print(np.full((1, 2), 7, dtype=np.int))
array([[7, 7]])
a = np.linspace(0, 1, 5)
print(a)
# array([ 0. , 0.25, 0.5 , 0.75, 1. ])
# full_like 接受數組,并取形狀
# full_like(arr, val) 等價于 ones(arr.shape) * val
print(np.full_like(a, 7))
# array([ 7., 7., 7., 7., 7.])
print(np.full_like(a, 7, dtype=np.int))
# array([7, 7, 7, 7, 7])
np.random.choice 随機選取
# 取 400 個随機數,滿足 B(5, 0.5)
N = 400
np.random.seed(28)
data = np.random.binomial(5, .5, size=N)
# 從随機數中随機取 400x30 個值
# 等價于選取 Nx30 次
# 每次使用 randint(0, len(data)) 來生成下标
bootstrapped = np.random.choice(data, size=(N, 30))
# 計算每列的均值
means = bootstrapped.mean(axis=0)
# 繪制盒圖(包含最大值、最小值、中位數、兩個四分位數)
plt.title('Bootstrapping demo')
plt.grid()
plt.boxplot(means)
plt.plot(3 * [data.mean()], lw=3, label='Original mean')
plt.legend(loc='best')
plt.show()
datetime64 類型
import numpy as np
# 由年月日構造
print(np.datetime64('2015-05-21'))
# numpy.datetime64('2015-05-21')
# 去掉橫杠
print(np.datetime64('20150521'))
# 由年月構造
print(np.datetime64('2015-05'))
# numpy.datetime64('20150521')
# numpy.datetime64('2015-05')
# 由日期和時間構造
local = np.datetime64('1578-01-01T21:18')
print(local)
# numpy.datetime64('1578-01-01T21:18Z')
# 可以帶上偏移
with_offset = np.datetime64('1578-01-01T21:18-0800')
print(with_offset)
# numpy.datetime64('1578-01-02T05:18Z')
# datetime64 作差會生成 timedelta64
print(local - with_offset)
# numpy.timedelta64(-480,'m')