python3.5版本下demo实例
import sys
import numpy
print(sys.version)
'''
3.5.3 |Continuum Analytics, Inc.| (default, May 15 2017, 10:43:23) [MSC v.1900 64 bit (AMD64)]
'''
print ('使用列表生成一维数组')
data = [1,2,3,4,5,6]
x = numpy.array(data)
print (x )#打印数组
print (x.dtype) #打印数组元素的类型
'''
[1 2 3 4 5 6]
int32
'''
print ('使用列表生成二维数组')
data = [[1,2,2],[3,4,2],[5,6,2],[5,6,2]]
x = numpy.array(data)
print (x) #打印数组
print (x.ndim) #打印数组的维度
print (x.shape) #打印数组各个维度的长度。shape是一个元组
'''
[[1 2 2]
[3 4 2]
[5 6 2]
[5 6 2]]
2
(4, 3)
'''
print ('使用zero/ones/empty创建数组:根据shape来创建')
x = numpy.zeros(6) #创建一维长度为6的,元素都是0一维数组
print (x)
x = numpy.zeros((2,3)) #创建一维长度为2,二维长度为3的二维0数组
print (x)
x = numpy.ones((2,3)) #创建一维长度为2,二维长度为3的二维1数组
print (x)
x = numpy.empty((3,3)) #创建一维长度为2,二维长度为3,未初始化的二维数组
print (x)
'''
[ 0. 0. 0. 0. 0. 0.]
[[ 0. 0. 0.]
[ 0. 0. 0.]]
[[ 1. 1. 1.]
[ 1. 1. 1.]]
[[ 2.45757305e-315 2.45761635e-315 2.45761635e-315]
[ 2.45761635e-315 2.45761635e-315 2.45761635e-315]
[ 0.00000000e+000 0.00000000e+000 2.71797014e-316]]
'''
print ('使用arrange生成连续元素')
print (numpy.arange(6) )# [0,1,2,3,4,5,] 开区间
print (numpy.arange(0,6,2) ) # [0, 2,4]
'''
[0 1 2 3 4 5]
[0 2 4]
'''
print ('生成指定元素类型的数组:设置dtype属性')
x = numpy.array([1,2.6,3],dtype = numpy.int64)
print (x )# 元素类型为int64
print (x.dtype)
x = numpy.array([1,2,3],dtype = numpy.float64)
print (x) # 元素类型为float64
print (x.dtype)
'''
[1 2 3]
int64
[ 1. 2. 3.]
float64
'''
print ('使用astype复制数组,并转换类型')
x = numpy.array([1,2.6,3],dtype = numpy.float64)
y = x.astype(numpy.int32)
print (y) # [1 2 3]
print (x) # [ 1. 2.6 3. ]
z = y.astype(numpy.float64)
print (z) # [ 1. 2. 3.]
'''
[1 2 3]
[ 1. 2.6 3. ]
[ 1. 2. 3.]
'''
print ('将字符串元素转换为数值元素')
x = numpy.array(['1','2','3'],dtype = numpy.string_)
y = x.astype(numpy.int32)
print (x )# ['1' '2' '3']
print (y )# [1 2 3] 若转换失败会抛出异常
'''
[b'1' b'2' b'3']
[1 2 3]
'''
print ('使用其他数组的数据类型作为参数')
x = numpy.array([ 1., 2.6,3. ],dtype = numpy.float32);
y = numpy.arange(3,dtype=numpy.int32);
print (y) # [0 1 2]
print (y.astype(x.dtype)) # [ 0. 1. 2.]
'''
[0 1 2]
[ 0. 1. 2.]
'''
numpy基本类型