numpy 编码练手
一,numpy 的功能
支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。
二,代码练习
# coding=utf-8
import numpy as np
import matplotlib as mpl
# Ndarray set of same type elements , index from 0. N dimension,
a_ndarray = np.array([1, 2, 3])
# 数据类型也是一个类
dt = np.dtype(np.int32)
print (dt)
student = np.dtype([('name', 'S20'), ('age', 'i1'), ('marks', 'f4')])
a = np.array([('abc', 21, 50), ('xyz', 18, 75)], dtype=student)
print (a)
# np array https://www.runoob.com/numpy/numpy-array-manipulation.html#numpy_oparr2
# attribute and creation
a = np.empty([3, 2], dtype=int) # np.ones()
print (a.shape)
# np.asarray() 列表 元组 多维数组 dtype order
x = [1, 2, 3]
a = np.asarray(x)
print (a)
# np.fromiter() 迭代器 np.frombuffer() 流的形式读入
s = b'Hello World'
a = np.frombuffer(s, dtype='S1')
print (a)
list = range((5))
it = iter(list)
x = np.fromiter(it, dtype=float)
print (x)
x1 = np.arange(5, dtype=float) # arange
print (x1)
x2 = np.linspace(1, 10, 10) # logspace() 等比等差数列
print x2
# indexing and sliceing
arr_slice = np.arange(10)
sliced = slice(2, 7, 2)
print (arr_slice[sliced]) # arr_slice[2:7:2] [2] [2:7]
# 多维数组分片类似, 一个维度切片,比如行方向
a_2arr = np.array([[1, 2, 4], [3, 4, 5], [6, 7, 8]])
print (a_2arr[..., 1:]) # 行位置, 第2列。
# advanced indexing 整数数组索引、布尔索引及花式索引。
'''
用数组定位元素 [0,1,2], [0,1,0] , (0,0) (1,1)...
行索引是[0, 0]和[3, 3],而列索引是[0, 2]和[0, 2]。 四个角元素
print (x[x > 5]) a[~np.isnan(a)]
花式索引: 利用整数数组进行索引。 任意定位元素
'''
hua_idx_arr = np.arange(32).reshape((8, 4))
print("数组索引例子")
print(hua_idx_arr[[1, 5, 3], [1, 3, 2]])
print(hua_idx_arr[np.ix_([1, 5, 3], [1, 3, 2])]) # 多个索引数组
# ndarray 计算
'''
# 广播: 强行一致shape 对数组的算术运算通常在相应的元素上进行。
迭代:
遍历顺序,行优先
nditer(a, order='F') 列序优先 / c = b.copy(order='F')
修改元素:
for x in np.nditer(iter_a, op_flags=['readwrite']):
x[...]=2*x
遍历每列:for x in np.nditer(a, flags = ['external_loop'], order = 'F'):
广播迭代:
操作: shape invert dimension join split add/delete element
reshape:
flat: for element in a.flat: 可元素处理
flatten: 返回数组拷贝 不影响
ravel: 数组视图,修改影响原数组
对换维度 transpose, 索引下标对换 a.T
后滚动rollaxis,
换轴swapaxes
concatenate: stack hstack vstack
计算:位计算:bitwise_and invert left_shift 左移 对象:整数
字符串:对象,对 dtype 为 numpy.string_ 或 numpy.unicode_ 的数组
add multiply
np.char.center()
np.char.capitalize
数学函数: sin cos round
算术函数: add subtract multiply divide 要求:相同的形状或符合数组广播规则
统计:轴方向,amin amax percentile百分位数 median中位数 mean 标准差std 方差var
1: 行轴 按列排序
0:列轴
排序,条件筛选函数: sort(a, axis, kind, order)
返回排序副本, 排序类型:quicksort
帅选:np.nonzero() 非零元素索引
np.where(x > 3) 给定条件 extract(condition)
condition = np.mod(x,2) == 0
副本和视图:副本不会影响元数据,发生在: 切片,用deepCopy() ndarray.copy()
视图: np的切片返回视图, view函数 ;修改维数,不影响;切片后不同id,元素影响
操作模式: 无复制:引用赋值, 原位修改
视图:arr.view
'''
iter_a = np.arange(6).reshape(2, 3)
print "基础遍历"
for x in np.nditer(iter_a):
print (x)
print('\n')
write_arr = np.arange(0, 60, 5).reshape(3, 4)
for x in np.nditer(write_arr, op_flags=['readwrite']):
x[...] = 2 * x
print('修改后的数组是:')
print (write_arr)
flatten_arr = np.arange(8).reshape(2, 4)
print(flatten_arr.flatten(order='F')) #按列,数组副本
math_arr = np.array([0, 30, 45, 60, 90])
print("计算正弦值")
print(np.sin(math_arr * np.pi / 180))
sort_dt = np.dtype([('name', 'S10'), ('age', int)])
sort_arr = np.array([("raju", 21), ("anil", 25), ("ravi", 17), ("amar", 27)],
dtype=sort_dt)
print("按标签列排序")
print (np.sort(sort_arr, order='name'))
ages = [5,10 ,56,34 ,67, 3 ,45]
print (np.percentile(ages, 75))
# matlib 矩阵库 linalg:电积 内积 矩阵积
代码运行结果;(部分截图)
---一------步-----一 ------个-----脚--------印----------