numpy的ndarray学习笔记
1.numpy最重要的一个特点就是其N维数组对象(ndarray),该对象是一个快速而灵活的大数据集容器。
# -- coding: utf-8 --
import numpy as np
data=np.array([[0.9526,0.246,0.8856],[0.5639,0.2379,0.9104]])
2.ndarray是一个通用的同构数据多维容器,也就是说,其中的所有元素必须是相同类型的。
#shape 一个表示各维度大小的元组
print data.shape
#dtype 一个用于说明数组数据类型的对象
print data.dtype
输出结果
(2L, 3L)
float64
3.除np.array外,还有一些函数可以创建数组。比如zeros和ones分别可以创建指定长度或形状的全0或全1数组。empty可以创建一个没有任何具体值的数组。要用这些方法创建多维数组,只需要传入一个表示形状的元组即可。
empty创建数组,只分配内存空间但不填充任何值
print np.zeros(10)
print np.zeros((3,6))
输出结果
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]]
print np.empty((2,3,2))
输出结果
[[[ 2.98129453e-316 6.38722586e-314]
[ 2.12496290e-316 2.96439388e-323]
[ 1.91192280e-313 0.00000000e+000]]
[[ 5.92878775e-323 3.18299369e-313]
[ 0.00000000e+000 4.03179200e-313]
[ 0.00000000e+000 1.08694442e-322]]]
注意:认为np.empty会返回全0数组的想法是不安全的。很多情况下,它返回的都是一些未初始化的垃圾值。
4.arange是python内置函数range的数组版本:
print np.arange(15)
输出结果
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
结果为0-14不包含15
5.指定ndarray的数据类型
arr1=np.array([1,2,3],dtype=np.float64)
arr2=np.array([1,2,3],dtype=np.int32)
print arr1.dtype
print arr2.dtype
输出结果
float64
int32
6.可以通过ndarray的astype方法显式的转换其dtype
arr = np.array([1,2,3,4,5])
print arr
print arr.dtype
float_arr=arr.astype(np.float64)
print float_arr
print float_arr.dtype
输出结果
[1 2 3 4 5]
int32
[ 1. 2. 3. 4. 5.]
float64
7.如果某字符串数组表示的全是数字,也可以用astype将其转换为数值形式:
numeric_strings = np.array(['1.25','-9.6','42'],dtype=np.string_)
res = numeric_strings.astype(float)
print numeric_strings
print res
输出结果
['1.25' '-9.6' '42']
[ 1.25 -9.6 42. ]
*注意:字母形式的字符串,无法转换成数值
注意:调用astype无论如何都会创建出一个新的数组(原始数据的一份拷贝),即使新dtype跟老dtype相同也是如此*