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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值