利用python进行数据分析——Numpy基础

这里主要是对《利用python进行数据分析》的学习,原书的电子版地址为:

https://github.com/iamseancheney/python_for_data_analysis_2nd_chinese_version
不知道这个项目是不是译者或者是什么好心人整理的。

这里主要记录下Numpy的常用内容。

ndarray

ndarray创建

ndarray对象的创建可以通过array函数完成,通过传入序列型对象,就可以据此产生对应的numpy数组。

一维数组
a = np.array(range(10))
print(a, type(a), a.shape, a.ndim)

结果为:

[0 1 2 3 4 5 6 7 8 9] <class 'numpy.ndarray'> (10,) 1
二维数组

二维数组可以通过传入多个嵌套序列进行转换:

a = np.array([range(10), range(10,20)])
print(a, type(a), a.shape, a.ndim)

结果为:

[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]] <class 'numpy.ndarray'> (2, 10) 2

也可以将一维数组转换为多维数组:

a = np.array(range(10)).reshape(1,10)
print(a, type(a), a.shape, a.ndim)

结果为:

[[0 1 2 3 4 5 6 7 8 9]] <class 'numpy.ndarray'> (1, 10) 2
dtype

保存在ndarray中的数据会有自己的数据类型,也可以指定对应的数据类型,该数据类型以dtype类型对象的形式封装:

a = np.array(range(10)).reshape(1,10)
print(a, a.dtype, type(a.dtype))

结果为:

[[0 1 2 3 4 5 6 7 8 9]] int32 <class 'numpy.dtype'>

这个是默认的推断数据类型,也可以指定数据类型:

a = np.array(range(10), dtype=np.float64).reshape(1,10)
print(a, a.dtype, type(a.dtype))

结果为:

[[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]] float64 <class 'numpy.dtype'>

numpy中数据类型有:

astype、asarray
  • astype:可以将ndarray对象的数据类型转换为其它数据类型
  • asarray:可以将序列类型转换为ndarray数组
np.array(range(4), dtype = np.int16).reshape(2,2).astype(np.float32)

 结果为:

array([[0., 1.],
       [2., 3.]], dtype=float32)

不过有时候转换时会进行数据转换的处理,比如float转int就会截断小数部分,如果不能完成转换,就会报ValueError。

asarray则可以将序列类型转换为ndarray数组:

np.asarray(range(4), dtype = np.float32).reshape(2,2)

结果为:

array([[0., 1.],
       [2., 3.]], dtype=float32)
 zeros、ones、empty、arange、eye
  • zeros:可以创建指定长度或形状的全0或全1数组
  • ones:可以创建指定长度或形状的全0或全1数组
  • empty:可以创建一个没有任何具体值的数组,即未初始化的垃圾值
  • arange:类似内置的range函数
  • eye:单位矩阵
a = np.zeros([2,2])
b = np.ones([2,2])
c = np.empty([2,2])
d = np.arange(4)
e = np.eye(2)
print(a,b,c,d,e,sep="\n\n")

结果为:

[[0. 0.]
 [0. 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值