# -*- coding: utf-8 -*-
"""
主要记录代码,相关说明采用注释形势,供日常总结、查阅使用,不定时更新。
Created on Fri Aug 24 19:57:53 2018

@author: Dev
"""

 

import numpy as np
import random
 
# 常用函数
arr = np.arange(10)
print(np.sqrt(arr))    # 求平方根
print(np.exp(arr))    # 求e的次方
 
random.seed(200)    # 设置随机种子
x = np.random.normal(size=(8, 8))
y = np.random.normal(size=(8, 8))
np.maximum(x, y)    # 每一位上的最大值
 
arr = np.random.normal(size=(2, 4)) * 5
print(arr)
print(np.modf(arr))    # 将小数部分与整数部分分成两个单独的数组
 
# 向量化操作
# meshgrid的基本用法
points1 = np.arange(-5, 5, 1)     # [-5, 5]闭区间步长为1的10个点
points2 = np.arange(-4, 4, 1)
xs, ys = np.meshgrid(points1, points2)    # 返回一个由xs, ys构成的坐标矩阵
print(xs)   # points1作为行向量的len(points1) * len(points2)的矩阵
print(ys)   # points2作为列向量的len(points1) * len(points2)的矩阵
 
# 将坐标矩阵经过计算后生成灰度图
import matplotlib.pyplot as plt
points = np.arange(-5, 5, 0.01)     # 生成1000个点的数组
xs, ys = np.meshgrid(points, points)
z = np.sqrt(xs ** 2 + ys ** 2)  # 计算矩阵的平方和开根
print(z)
plt.imshow(z, cmap=plt.cm.gray)
plt.colorbar()
plt. ("Image plot of $sqrt{x^2 + y^2}$ for a grid of values")
plt.show()
 
\"\"
 
# 将条件逻辑表达为数组运算
xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
cond = np.array([True, False, True, True, False])
# 纯Python,用列表解析式做判断
result = [x if c else y for x, y, c in zip(xarr, yarr, cond)]
# zip()基本用法
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
for tupple_a in zip(a, b, c):   # python 3.x为了减少内存占用,每次zip()调用只返回一个元组对象
    print(tupple_a)
 
# np.where()
result = np.where(cond, xarr, yarr)
 
 
# np.where()的用法:
 
收藏 打印