Numpy 机器学习三剑客之Numpy

NumPy是Python语言的一个扩充程序库。支持高级大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。Numpy内部解除了Python的PIL(全局解释器锁),运算效率极好,是大量机器学习框架的基础库!

Numpy简单创建数组

nlist = np.array([1,2,3])
print(nlist)
#[1 2 3]

Numpy查看数组属性

#ndim方法用来查看数组维度
print(nlist.ndim)   #2

#二维数组
nlist_2 = np.array([[1,2,3],[4,5,6]])
print(nlist_2)
print(nlist_2.ndim)

#[[1 2 3]
#  [4 5 6]]
#  2

#使用shape属性来大印多维数组的形状
print(nlist.shape,nlist_2.shape)
#(3,) (2, 3)

#使用size方法来打印多维数组的元素个数
print(np.size(nlist))
print(np.size(nlist_2))
# 3
# 6

#打印numpy多维数组的数据类型
print(type(nlist))
#<class 'numpy.ndarray'>

#使用dtype属性打印多维数组内部元素的数据类型
print(nlist.dtype)
#itemsizes属性,多维数组中的数据类型大小,字节
print(nlist.itemsize)
#data属性 打印数据缓冲区 buffer
print(nlist.data)
# int32
#   4
#  <memory at 0x0000023047DB5C48>

快速创建N维数组的api函数

#使用ones方法,自动生成元素为1的多维数组
nlist_ones = np.ones((4,4))
print(nlist_ones)
print(nlist_ones.dtype)

#[[1. 1. 1. 1.]
# [1. 1. 1. 1.]
# [1. 1. 1. 1.]
# [1. 1. 1. 1.]]
#float64

#zeros
nlist_zeros = np.zeros((4,4))
print(nlist_zeros)
#[[0. 0. 0. 0.]
# [0. 0. 0. 0.]
# [0. 0. 0. 0.]
# [0. 0. 0. 0.]]

#使用empty方法来生成随机多维数组,使用第二参数指定数据类型
  nlistempty = np.empty([2,2])
 nlist_empty = np.empty([2,2],dtype= np.int)
print(nlistempty)
 print(nlist_empty)
#[[5.e-324 5.e-324]
# [0.e+000 0.e+000]]
#[[0 0]
# [0 0]]

使用reshape方法来反向生成多维数组
nlist_3 = np.array(range(24)).reshape((3,2,4))
print(nlist_3)
print(nlist_3.shape)
nlist_float = np.array([1.0,2.0])
print(nlist_float.dtype)
#使用字符串
nlist_string=np.array(['1','2','3'])
print(nlist_string.dtype)

#[[[ 0  1  2  3]
#  [ 4  5  6  7]]
#
# [[ 8  9 10 11]
#  [12 13 14 15]]
#
# [[16 17 18 19]
#  [20 21 22 23]]]
#(3, 2, 4)
#float64
#<U1
把普通list转换为数组
x = [1,2,3]
x = [(1,2,3),(4,5)]
nlist = np.asarray(x)
print(nlist)

#[(1, 2, 3) (4, 5)]
frombuffer 通过字符串(buffer内存地址)切片来生成多维数组
my_str = b"hello world"
nlist_str = np.frombuffer(my_str,dtype='S1')
print(nlist_str)

#[b'h' b'e' b'l' b'l' b'o' b' ' b'w' b'o' b'r' b'l' b'd']
axis 属性可以指定当前多维数组的维度(0表示行,1表示列 keepdims表示结构)
sum0 = np.sum(x,axis=0,keepdims=False)
print(sum0)
sum1 = np.sum(x,axis=1,keepdims=1)
sum = np.sum(x,axis=1,keepdims=0)
print(sum1,sum)

#[4 6]
#[[3]
# [7]]
#[3 7]
维度级的运算
a = np.array([[1,2],[3,4],[5,6]])
b = np.array([[10,20],[30,40],[50,60]])

#vstack方法
suma = np.vstack((a,b))
print(suma)
print("-"*30)
#hstack方法
sumb = np.hstack((a,b))
print(sumb)

#[[ 1  2]
#[ 3  4]
# [ 5  6]
# [10 20]
# [30 40]
# [50 60]]
------------------------------
#[[ 1  2 10 20]
# [ 3  4 30 40]
# [ 5  6 50 60]]
多维数组的调用
nlist=np.array([[1,2],[3,4],[5,6]])
print(nlist[1][1])
print(nlist[1,1])
#删除方法 delete
#s删除nlist第二行
print(np.delete(nlist,1,axis=0))
print(np.delete(nlist,0,axis=1))

#4
#4
#[[1 2]
# [5 6]]
#[[2]
# [4]
# [6]]

**未完待续

猜你喜欢

转载自www.cnblogs.com/xcsg/p/10461095.html