您的位置:首页 > 编程语言 > Python开发

python Numpy—— 数组array

2018-02-27 13:25 696 查看
知乎:CS231n课程笔记翻译:Python Numpy教程
好书:《python科学计算》
1.np.newaxis 用于增加数组的维度
def test():
#增加新维度
a = np.array(np.random.randint(1,10,10))  # 一维数组
print(a, a.shape)
print('-----------------')
b = a[np.newaxis,:]  #增加维度,1*10  二维数组
c = a[:, np.newaxis] #10*1数组
print(b, b.shape)
print(c, c.shape)

if __name__ == '__main__':
test()
[3 3 2 8 2 6 8 6 2 6] (10,)      #a 一维数组
-----------------
[[3 3 2 8 2 6 8 6 2 6]] (1, 10)  #b 二维数组  1行10列
[[3]                             #c 二维数组  10行1列
[3]
[2]
[8]
[2]
[6]
[8]
[6]
[2]
[6]] (10, 1)

2.python 字符串 h = 'hello'
w = 'world'
hw = '%s %s %d' % (h, w, 3) #prints "hello world 3"
print(hw)
# print(h.capitalize()) #Hello 首字母大写 其他小写
# print(h.rjust(16)) #右移16个空格
# print(h.center(16)) # 左右各有16个空格 " hello "
print(h.replace('l','(ell'))3.numpy数组def numpyTest():
import numpy as np
a = np.array([1, 2, 3]) #创建一维数组 [1 2 3] (3,)
a = np.arange(4)
b = np.array([[1, 2, 3], [4, 5, 6]]) #创建二维数组 [[1 2 3][4 5 6]] (2, 3)
c = np.array([[[1, 2, 3], [4, 5, 6]],[[1, 2, 3], [4, 5, 6]]]) # 创建二维数组
print(a,a.shape,type(a))
print('--------二维数组------------')
print(b, b.shape, type(b))
print('---------三维数组-----------')
print(c, c.shape, type(c))

#其他创建数组的方法
print('---------2行2列全0矩阵-----------')
d = np.zeros((2,2)) #创建2行2列全0矩阵
print(d)

print('---------2行2列全1矩阵-----------')
e = np.ones((2,2)) #创建2行2列全1矩阵
print(e)

print('---------2行2列全8矩阵-----------')
f = np.full((2,2), 8) #创建2行2列全8矩阵
print(f)

print('----------2行2列单位矩阵----------')
g = np.eye(2) # 创建2行2列单位矩阵
print(g)

print('----------2行2列随机矩阵----------')
h = np.random.random((2,2)) #创建2行2列随机矩阵
print(h)

print('----------2行2列随机矩阵(0-100之间)----------')
i = np.random.randint(0,100,(2,2))
print(i)

#-------------------访问数组-----------------
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
b = a[:2, 1:3] #0-2行的 1-3列
print('a: ',a, a.dtype) #元素类型
print('b: ', b)
print(a[[0, 1, 2], [0, 1, 0]]) #获取a中下标为(0,0),(1,1),(2,0)的元素
print(a[(0, 1, 2), (0, 1, 0)]) #和上边一样

if __name__ == '__main__':
# test()
# pytest()
numpyTest()
[0 1 2 3] (4,) <class 'numpy.ndarray'>
--------二维数组------------
[[1 2 3]
[4 5 6]] (2, 3) <class 'numpy.ndarray'>
---------三维数组-----------
[[[1 2 3]
[4 5 6]]

[[1 2 3]
[4 5 6]]] (2, 2, 3) <class 'numpy.ndarray'>
---------2行2列全0矩阵-----------
[[0. 0.]
[0. 0.]]
---------2行2列全1矩阵-----------
[[1. 1.]
[1. 1.]]
---------2行2列全8矩阵-----------
[[8 8]
[8 8]]
----------2行2列单位矩阵----------
[[1. 0.]
[0. 1.]]
----------2行2列随机矩阵----------
[[0.66268291 0.857943  ]
[0.73081994 0.26881019]]
----------2行2列随机矩阵(0-100之间)----------
[[28 25]
[63  0]]
a:  [[ 1  2  3  4]
[ 5  6  7  8]
[ 9 10 11 12]] int64
b:  [[2 3]
[6 7]]
[1 6 9]
[1 6 9]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: