Numpy快速入门(1): 矩阵创建与元素操作

2018-09-02  本文已影响0人  大锅烩菜

1. 需要先导入:

import numpy

2. 建立矩阵

import numpy
#创建矢量
vector = numpy.array([5,10,15,20])
# 创建矩阵
matrix = numpy.array([[3,6,9,11],[2,4,8,10],[1,5,7,9]]);

还能建立特殊矩阵:

a = numpy.zeros([4,5]) # all zero
a = numpy.ones([7,6],numpy.int32) # all one    numpy.int32可选
# 参数1起始值,参数二终止值,参数三步长
a = numpy.arange(10, 30, 5) # array([10, 15, 20, 25]), 1-D
# arange(12)会产生[0,11]的12个数字,reshape将其转换为3行4列的矩阵
a = numpy.arange(12).reshape(3,4) #
a = numpy.random.random((2,3)) # 随机数矩阵  (-1, 1)
a = numpy.linspace(0, 2, 9) # 9 numbers from 0 to 2
a = numpy.eye(4,7) # 4x7 diagonal
a = numpy.diag(range(5)) # 5x5 diagonal
a = numpy.empty((2,3))

def f(x,y):
    return x+y
a = numpy.fromfunction(f,(5,4),dtype=int) # 从函数f(x,y)建立

3.查看矩阵元素

print(vector.shape) #(4,)    表示矢量有4个元素
print(matrix.shape) # (3, 4) 表示矩阵为3行4列

4. 矩阵元素的数据类型需要是一致

python中List中可以添加不同类型的元素,但是在numpy矩阵中,元素的类型需要是一致的,如果不一致,会自动进行类型转换。例如:

import numpy
vector = numpy.array([3,4,3.14])
print(vector)
vector.dtype  # 打印数据类型

输出结果:

[3.   4.   3.14]
Out[1]:dtype('float64')

发现3,4的值变为了3.,4.,成了浮点数。

5.读取文本

# genfromtxt第一个参数是必须的,表示文件的路径。dtype表示读入后的数据类型,skip_header表示忽略第一行,delimiter表示自动转换时的分割符
s = numpy.genfromtxt("wine.txt",dtype=str,skip_header=1,delimiter=",")
print(s)

读取结果如下:

[['1986' 'Western Pacific' 'Viet Nam' 'Wine' '0']
 ['1985' 'Africa' 'Malawi' 'Other' '0.75']]

6. 元素的读取

matrix = numpy.array([[3,6,9,11],[2,4,8,10],[1,5,7,9]])
print(matrix[1,2])  # 8
matrix = numpy.array([[3,6,9,11],[2,4,8,10],[1,5,7,9]])
# 0:2 包左不包右。也就是索引是[0,1]即第一,第二个元素,
print(matrix[1,0:2])  # [2,4]
matrix = numpy.array([[3,6,9,11],[2,4,8,10],[1,5,7,9]])
print(matrix[:,2]) # [9 8 7]
matrix = numpy.array([[3,6,9,11],[2,4,8,10],[1,5,7,9]])
print(matrix[:,0:2])

-----------
[[3 6]
 [2 4]
 [1 5]]
matrix = numpy.array([[3,6,9,11],[2,4,8,10],[1,5,7,9]])
print(matrix[1:3,0:2])
-----------
[[2 4]
 [1 5]]
上一篇 下一篇

猜你喜欢

热点阅读