numpy - 学习笔记

2020-08-13  本文已影响0人  自走炮

基础

import numpy as np

myarray = [1,2,3,5,8,13]
nparray = np.array(myarray).reshape(2,3)
print(nparray)
print('数组维数:', nparray.ndim)
print('数组维数(元组tuple类型:行列形式)', nparray.shape)
print('数组元素个数', nparray.size)
print('数组元素类型', nparray.dtype)
print('数组单个元素占用内存字节', nparray.itemsize)

随机数 正态分布

from numpy.random import * # 随机数生成

print(rand()) # 生成1个0-1的随机数
print(rand(5)) # 生成5个0-1的随机数数组
print(rand(3,2)) # 生成3行2列的0-1的随机数数组

print(randint(100)) # 生成1个0-99的随机数
print(randint(10,20)) # 生成1个10-19的随机数
print(randint(10,20,5)) # 生成5个10-19的随机数数组
print(randint(10,20,(2,3))) # 生成2行3列的10-19的随机数数组

players = ["curry", "harden", "lebron", "durant", "antetokounmpo", "westbrook", "McGee"]
print(choice(players)) # 随机抽出一个球员
print(choice(players, 3)) # 随机抽出3个球员(有重复)
print(choice(players, 3, replace=False)) # 随机抽出3个球员(无重复)

print(randn()) # 标准正态分布(平均:0, 偏差:1)
print(randn(5)) # 生成5个元素的正态数组
print(randn(5,5)) # 生成5行5列的正态数组

import matplotlib.pyplot as plt

R = randn(10000) # 生成1万个标准正态分布数组
plt.hist(R, bins=100) # 图形化显示(直方图)
plt.show()

数组连结 数组分割

a = np.arange(5)
b = np.arange(10, 15)
print(a)
print(b)
print(np.concatenate([a, b])) # 数组连结
c = np.arange(20, 25)
print(c)
print(np.concatenate([a, b, c])) # 数组连结

a1 = np.array([
    [1,2,3],
    [7,8,9]
])
a2 = np.array([
    [10,20,30],
    [70,80,90]
])
print(a1)
print(a2)
print(np.concatenate([a1, a2])) # 竖向拼接
print(np.concatenate([a1, a2], axis=1)) # 横向拼接

print(np.vstack([a1, a2])) # vstack
print(np.hstack([a1, a2])) # hstack

a = np.arange(8)
print(a)
print(np.split(a, [3])) # 数组分割
print(np.split(a, [3, 6])) # 数组分割

b = np.arange(16).reshape(4,4)
print(b)
upper, lower = np.vsplit(b, [2]) # 垂直方向,横向出刀
print(upper)
print(lower)
left, right = np.hsplit(b, [2]) # 水平方向,竖向出刀
print(left)
print(right)

计时器

import timeit # timeit 计时 估算代码执行时间

a = np.random.rand(1000)

def f1():
    b = np.empty(len(a))
    for i in range(len(a)):
        b[i] = 1 / a[i]
    return b

def f2():
    b = 1 / a
    return b

print(timeit.timeit(stmt=f1, number=1000))
print(timeit.timeit(stmt=f2, number=1000))

数组积累

a = np.arange(1, 6)
print(a)

b = np.add.reduce(a) # reduce 数组积累函数
print(b)

c = np.multiply.reduce(a)
print(c)

b = np.add.accumulate(a) # accumulate 数组积累函数(保留中间结果)
print(b)

c = np.multiply.accumulate(a)
print(c)
上一篇下一篇

猜你喜欢

热点阅读