首先导入import模块
import numpy as np
创建list和matrix
vector = np.array([5, 10, 15, 20]) # list
matrix = np.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]]) # matrix
print vector
print matrix
#打印输出
[ 5 10 15 20]
[[ 5 10 15]
[20 25 30]
[35 40 45]]
求取矩阵的各种属性
print(vector.shape) #打印list形状
print(matrix.shape) #打印矩阵形状
#打印输出
(4L,)
(3L, 3L)
numbers = np.array([1, 2, 3, 4])
numbers.dtype #输出list的数据类型
#打印输出
dtype('int32')
提取矩阵元素
vector = numpy.array([5, 10, 15, 20])
print(vector[0:3])
#打印输出
[ 5 10 15]
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
print(matrix[:,1])
#打印输出
[10 25 40]
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
print(matrix[:,0:2])
[[ 5 10]
[20 25]
[35 40]]
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
print(matrix[1:3,0:2])
[[20 25]
[35 40]]
==操作
vector = numpy.array([5, 10, 15, 20])
vector == 10
#打印输出
array([False, True, False, False], dtype=bool)
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
matrix == 25
array([[False, False, False],
[False, True, False],
[False, False, False]], dtype=bool)
vector = numpy.array([5, 10, 15, 20])
equal_to_ten = (vector == 10)
print equal_to_ten
print(vector[equal_to_ten])
#打印输出
[False True False False]
[10]
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
second_column_25 = (matrix[:,1] == 25)
print second_column_25
print(matrix[second_column_25, :])
[False True False]
[[20 25 30]]
vector = numpy.array([5, 10, 15, 20])
equal_to_ten_and_five = (vector == 10) & (vector == 5)
print equal_to_ten_and_five
[False False False False]
vector = numpy.array([5, 10, 15, 20])
equal_to_ten_or_five = (vector == 10) | (vector == 5)
print equal_to_ten_or_five
[True True False False]
vector = numpy.array([5, 10, 15, 20])
equal_to_ten_or_five =