numpy实用技巧(一)

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)