numpy 学习笔记

numpy 学习笔记

导入 numpy 包

import numpy as np

声明 ndarray 的几种方法

方法一,从list中创建

l = [[1,2,3], [4,5,6], [7,8,9]]
matrix = np.array(l)
print(matrix)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

方法二,指定维度,不赋值

matrix = np.ndarray(shape=(3,4))
print(matrix)
[[9.66308774e-312 2.47032823e-322 0.00000000e+000 0.00000000e+000]
 [1.89146896e-307 2.42336543e-057 5.88854416e-091 9.41706373e-047]
 [5.44949034e-067 1.46609735e-075 3.99910963e+252 3.43567991e+179]]

由上述的输出可见,矩阵内部的值未初始化,其实这都是原来对应内存地址中的数值

方法三,指定维度,初始化成全零的矩阵

matrix = np.zeros(shape=[3,4])
print(matrix)
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

方法四,使用默认参数(arange),生成从0至arange的一组数据

matrix = np.arange(12).reshape(3,4)
print(matrix)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

数值计算

操作全部元素

print(matrix)
print("after times 10 on every elements:")
print(matrix * 10)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
after times 10 on every elements:
[[  0  10  20  30]
 [ 40  50  60  70]
 [ 80  90 100 110]]
print(matrix)
print("after plus 10 on every elements:")
print(matrix + 10)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
after plus 10 on every elements:
[[10 11 12 13]
 [14 15 16 17]
 [18 19 20 21]]

操作部分元素

print(matrix)
print("after times 10 on every elements:")
print(matrix[1] * 10)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
after times 10 on every elements:
[40 50 60 70]

索引部分元素

取一行数据

print(matrix)
print("a line of a matrix:")
print(matrix[1])
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
a line of a matrix:
[4 5 6 7]

取一列数据

以行的形式返回,得到一个行向量

print(matrix)
print("a column of a matrix:")
print(matrix[:,1])
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
a column of a matrix:
[1 5 9]

以列的形式返回,得到一个列向量

print(matrix)
print("a column of a matrix:")
print(matrix[:,1:2])
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
a column of a matrix:
[[1]
 [5]
 [9]]

参考资料

《利用python进行数据分析》. https://book.douban.com/subject/25779298/
Numpy. Quickstart tutorial. https://docs.scipy.org/doc/numpy/user/quickstart.html

猜你喜欢

转载自www.cnblogs.com/fengyubo/p/9092665.html
今日推荐