numpy实用技巧(一)
2016-01-09 17:35
441 查看
import numpy as np
功能 | 函数 |
---|---|
设置打印输出的精度 | np.set_printoptions(precision=4) |
一维数组构成的list,再进行像数组的转换
是以行的形式(而非列的形式)在拼接;>>> X = np.random.randn(5, 3) >>> ops = [np.argmax, np.argmin] >>> np.asarray([op(X, 1) for op in ops]) [[1 2 2 2 2] [2 0 1 1 1]]
两个向量的拼接
例如两个长度为 n 的一维向量,拼接为 2×n 的矩阵,可以使用np.vstack(),>>> x, y = np.ones(3), np.zeros(3) >>> np.vstack((x, y)) array([[ 1., 1., 1.], [ 0., 0., 0.]])
也可使用作为np.array()构造函数的参数,进行创建:
>>> np.array([x, y]) array([[ 1., 1., 1.], [ 0., 0., 0.]])
xx, yy = np.meshgrid(np.arange(, , ), np.arange(, , )) z = clf.predict(np.array([xx.ravel(), yy.ravel()]).T) z = z.reshape(xx.shape) plt.contoutf(xx, yy, z, alpha=.4, cmap=cmap)
numpy.ndarray的遍历
>>> X = np.random.randn(3, 3) array([[-0.24882132, -0.32389773, -0.96069467], [ 1.26331248, 1.59089579, -0.97145676], [-0.03989954, 0.28587614, 0.04657364]]) >>> for i in X: print(i) [-0.24882132 -0.32389773 -0.96069467] [ 1.26331248 1.59089579 -0.97145676] [-0.03989954 0.28587614 0.04657364] >>> for i in X: for j in i: print j -0.248821323982 -0.32389773407 -0.960694672326 1.26331248229 1.59089578902 -0.971456755866 -0.0398995441063 0.285876139182 0.0465736443469
numpy.ndarray()类型转换
有时编译器会报如下的错误:TypeError: Cannot cast array data from dtype(‘float64’) to
dtype(‘int32’) according to the rule ‘safe’
>>> print(np.bincount(y_train)) TypeError: Cannot cast array data from dtype('float64') to dtype('int32') according to the rule 'safe'
如果我们使用python基本模块下的强制类型转换,又会提示如下的错误:
>>> print(np.bincount(int(y_train))) TypeError: only length-1 arrays can be converted to Python scalars
此时可以使用x.astype(type)成员
>>> print(np.bincount(y_train.astype(np.int32))
二维数组的逆序
列向的逆序 A[:, -1::-1]:>>> np.set_printoptions(precision=4) >>> A = np.random.randn(3, 3) >>> A array([[ 1.2381, -0.2428, -0.4687], [-1.0588, 0.0432, 0.9937], [ 0.2708, 1.4833, 0.2697]]) >>> A[:, -1::-1] array([[-0.4687, -0.2428, 1.2381], [ 0.9937, 0.0432, -1.0588], [ 0.2697, 1.4833, 0.2708]])
行向的逆序:A[-1::-1, :]
>>> A[-1::-1, :] array([[ 0.2708, 1.4833, 0.2697], [-1.0588, 0.0432, 0.9937], [ 1.2381, -0.2428, -0.4687]])
references
basics types in Numpy相关文章推荐
- python文件处理方式
- python之线程学习
- python面向对象特性----mutable, immutable, 函数传参
- python crc计算器
- python新手笔记之python继承
- Python新手笔记之python迭代器遍历列表
- python新手笔记之包和模块的引入
- python新手笔记之python高级函数编程
- python学习――――模块subprocess
- Python Flask 开发环境搭建(Windows)
- ubuntu14.04 server python3.4 安装 numpy scipy matplotlib
- 使用python 提取网页的特定数据转
- python入门笔记(Day4)--map,reduce
- Python FTP 文件上传 例程
- ubuntu14.04 server python2.7 安装 numpy scipy matplotlib
- python运维笔记第一节
- ubuntu14.04 server python3 安装matplotlib失败及解决方法
- python大小写转换
- python文件中 `if __name__ == '__main__':` 的作用
- Python——问题解决方法整理