import numpy as np_最新Python学习教程(Python学习路线):Numpy常用用法总结

6c88a819f075f9161ebbcd12c8e64496.png

最新Python学习教程(Python学习路线):Numpy常用用法总结

一、前言

玩数据分析、数据挖掘、AI的都知道这个python库用的是很多的,里面包含各种操作,在实际的dataset的处理当中是非常常用的,这里我做一个总结,方便自己看,也方便大家看,我准备做一个非常细致的分类,每个分类有对应的numpy常用用法,以后见到或者用到再一个个慢慢加进来,如果我还用csdn我就会移植update下去。

二、下载、安装、导入

用anaconda安装是十分方便的,如果你已经安装了tf,keras之类的,其实已经直接把numpy安装了,一般来说安装就是pip命令。

1pip install numpy #py2
2pip3 install numpy #py3

用法:

1import numpy as np # 一般as为np来操作

三、常用用法总结

1.array基本信息以及生成各种常见array基本操作 

生成array,得到对应的基本信息

 1import numpy as np
 2
 3array = np.array([[1, 2, 3],
 4 [2, 3, 4]])
 5
 6print array #numpy生成的array
 7print array.dtype # 每个元素的类型
 8print "number of dim", array.ndim # array的维度
 9print 'shape:', array.shape #形状, 两行三列。
10print 'size:', array.size #array的大小=array中所有元素的个数
11"""
12 [[1 2 3]
13 [2 3 4]]
14 int64
15 number of dim 2
16 shape: (2, 3)
17 size: 6
18"""

array的生成就是np.array(list),本质上是把定义的list转换成array,因为array可以进行更加方便地计算和操作,比如矩阵的转置和相乘。

array的dtype设置

 1import numpy as np
 2
 3a = np.array([2, 23, 4], dtype=np.float32)
 4print "a's dtype", a.dtype
 5aa = np.array([2, 23, 4], dtype=np.int)
 6print "aa's dtype", aa.dtype
 7aaa = np.array([2, 23, 4])
 8print "aaa's dtype", aaa.dtype
 9aaaa = np.array([2.2, 23.2, 4.2])
10print "aaaa's dtype", aaaa.dtype
11aaaaa = np.array([2, 23, 4], dtype=np.int64)
12print "aaaaa's dtype:", aaaaa.dtype
13
14"""
15 a's dtype float32
16 aa's dtype int64
17 aaa's dtype int64
18 aaaa's dtype float64
19 aaaaa's dtype: int64
20"""

由可以得到一个结论就是如果定义的array里面的list的元素本身为整数的话,不设置type,则默认为int64,如果设置为int类型而没有设置字节大小则还是默认为int64,如果元素本身为小数,则默认为float64。

所以如果用int64,则如果元素都为整数则不需要设置默认即可,设置其他类型需要设置,float类似。

生成常见array格式

 1a1 = np.zeros((2, 3), dtype=np.int) # 生成shape=(2, 3)的全为0的array
 2
 3print a1
 4"""
 5 [[0 0 0]
 6 [0 0 0]]
 7"""
 8
 9a2 = np.ones((3, 4), dtype=np.int16) # 生成shape=(3, 4)的全为1的array
10
11print a2
12"""
13 [[1 1 1 1]
14 [1 1 1 1]
15 [1 1 1 1]]
16"""

这里注意shape=(a,b),在填入shape的参数的时候一定要加括号,以下雷同。

 1a3 = np.empty((3, 4)) # 生成shape=(3, 4)的全为接近空的array
 2print a3
 3"""
 4 [[6.92259773e-310 4.67497449e-310 6.92259751e-310 6.92259750e-310]
 5 [2.37151510e-322 3.16202013e-322 0.00000000e+000 6.92257087e-310]
 6 [6.92259748e-310 6.92257087e-310 6.92257063e-310 6.92257063e-310]]
 7"""
 8a4 = np.arange(10, 20, 2)  # 生成array 
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值