科学计算库Numpy基础操作

Posted mjerry

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了科学计算库Numpy基础操作相关的知识,希望对你有一定的参考价值。

pycharm,python3.7,numpy版本1.15.1

2018年9月11日04:23:06

 

"""
    科学计算库Numpy基础操作
    时间:2018911 0011
"""
import numpy

print("""
------以矩阵的方式读取数据------

------------genfromtxt函数(‘文件路径‘,delimiter = ‘分隔符‘,dtype = 读取方式)---------------------""")
"""
    numpy.ndarray可以当做一个矩阵
"""
np_test = numpy.genfromtxt(Numpy_test.txt, delimiter = ,, dtype = str)  # 通常以str方式读取,如果有float,再进行转换
print(type(np_test))
print(np_test)
# print(help(numpy.genfromtxt))  # 打印帮助文档


print("""
------numpy.array------

------------numpy中最核心的结构------------------------------------------""")
# 传入list结构,转换为ndarray格式
vector = numpy.array([5, 10, 15, 20])  # 创造一维矩阵
matrix = numpy.array([
    [5, 10, 15],
    [20, 25, 30],
    [35, 40, 45]
])  # 创造二维矩阵
print(vector)
print(matrix)

print("""
------print(numpy对象.shape)------

------------打印矩阵结构(例如2×3,3×3之类)------------------------------------------""")
vector = numpy.array([1, 2, 3, 4])
print(vector.shape)
matrix = numpy.array([
    [1, 2, 3],
    [4, 5, 6]
])
print(matrix.shape)

print("""
------numpy.array结构------

------------内部结构必须相同------------------------------------------""")
numbers = numpy.array([1, 2, 3, 4])
print(numbers)
print(numbers.dtype)
numbers = numpy.array([1, 2, 3, 4.0])
print(numbers)
print(numbers.dtype)
numbers = numpy.array([1, 2, 3, 4])
print(numbers)
print(numbers.dtype)

print("""
------数据选取------

------------与python一样,通过索引读取数据------------------------------------------""")
data_test = numpy.genfromtxt(Numpy_test.txt, delimiter = ,, dtype = str)
print(data_test)
# 读取hanmeimei的国家
hmm_contry = data_test[2, 3]
print("hanmeimei的国家是:{0}".format(hmm_contry))

print("""
------切片选取------

------------与python一样,(起始值:终止值:步长)------------------------------------------""")
vector = numpy.array([5, 10, 15, 20])
print(vector[0:3])  # 左闭右开的区间
matrix = numpy.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])
print(matrix[:, 1])  # 取中间一列也就是每一行,第二个值
print(matrix[:, 0:2])  # 取头两列也就是每一行,第一到第二个值(0:1左开右闭,所以要写0:2)

print("""
------numpy判断------

------------判断某个元素是否在矩阵当中------------------------------------------""")
vector = numpy.array([5, 10, 15, 20])
matrix = numpy.array([
    [5, 10, 15],
    [20, 25, 30],
    [35, 40, 45]
])
print(vector == 10)
print(matrix == 10)
equal_to_ten = vector == 10  # 返回bool类型的值
print(vector[equal_to_ten])  # 当做索引
second_column_25 = (matrix[:, 1] == 25)  # 判断第二列是否有25的值
print(second_column_25)  # 对应每一行False  True False
print(matrix[second_column_25])
equal_to_ten_and_five = (vector == 10) & (vector == 5)  # 是同时否存在10和5,与操作
print(equal_to_ten_and_five)
equal_to_ten_or_five = (vector == 10) | (vector == 5)  # 是否存在10或5,或操作
print(equal_to_ten_or_five)
print(vector[equal_to_ten_or_five])

print("""
------numpy.array类型的改变------

------------astype()函数,数据类型转换------------------------------------------""")
vector = numpy.array([1, 2, 3])
print(vector.dtype)
print(vector)
vector = vector.astype(float)
print(vector.dtype)
print(vector)

print("""
------numpy.array求极值的操作------

------------min(),max()函数------------------------------------------""")
vector = numpy.array([5, 10, 15, 20])
print(vector.min())
print(vector.max())

print("""
------numpy.array按行求和,按列求和------

---------sum()方法---参数axis = 1按行,axis = 0按列------------------------------------------""")
matrix = numpy.array([
    [5, 10, 15],
    [20, 25, 30],
    [35, 40, 45]
])
print(matrix.sum(axis = 1))  # 按行求和
print(matrix.sum(axis = 0))  # 按列求和

print("""
------矩阵变换------

---------造矩阵:arange();矩阵变换:reshape()------------------------------------------""")
print(numpy.arange(15))
a = numpy.arange(15).reshape(3, 5)  # 3行5列
print(a)
print(a.shape)  # 矩阵a的行列
print(a.ndim)  # 维度
print(a.dtype)  # 数据类型
print(a.size)  # 元素个数

print("""
------初始化矩阵------

---------造0矩阵:zeros((元组表示矩阵行列))方法,创造1矩阵ones()方法------------------------------------------""")
zero_matrix = numpy.zeros((3, 5))
print(zero_matrix)
one_matrix = numpy.ones((2, 3, 4), dtype = numpy.int32)
print(one_matrix)

print("""
------序列矩阵------

---------aragne()方法------------------------------------------""")
sq_matrix = numpy.arange(10, 30, 5)  # 从10开始,不包括30,步长为5
print(sq_matrix)

print("""
------随机模块------

---------random((元组表示矩阵行列))方法------------------------------------------""")
ran = 10 * numpy.random.random((2, 3))
ran = ran.astype(numpy.int32)
print(ran)

print("""
------平均间隔矩阵------

---------linspase(起始值,最大值,个数)方法------------------------------------------""")
lins = numpy.linspace(0, 1.1, 20)
print(lins)

print("""
------向量运算------

---------加减乘方------------------------------------------""")
a = numpy.array([20, 30, 40, 50])
b = numpy.arange(4)
print(a)
print(b)
c = a - b
print(c)
c = c - 1
print(c)
print(b ** 2)  # 每一个值分别运算
print(a < 35)

print("""
------矩阵乘法------

---------对应位置乘法和点乘------------------------------------------""")
A = numpy.array([
    [1, 1],
    [0, 1]
])
B = numpy.array([
    [2, 0],
    [3, 4]
])
print(A矩阵:
{0}.format(A))
print(B矩阵:
{0}.format(B))
print(A*B对应位置相乘:
{0}.format(A * B))
print(A·B点乘:
{0}.format(A.dot(B)))
print(A·B点乘:
{0}.format(numpy.dot(A, B)))

print("""
------矩阵科学计算------

---------e的幂,平方根------------------------------------------""")
B = numpy.arange(3)
print(B)
print(numpy.exp(B))  # 每个元素的为指数,e为底的次方
print(numpy.sqrt(B))  # 每个元素的平方根

print("""
------矩阵操作------

---------向下取整floor(),矩阵转向量ravel(),向量转矩阵a.shape(),矩阵转置a.T-----------------------""")
a = numpy.floor(10 * numpy.random.random((3, 4)))
print(矩阵a:
{0}.format(a), 
)
print(a.ravel(), 
)  # 向量转矩阵
a.shape = (6, 2)  # 矩阵转向量
print(a, 
)
print(a.T, 
)  # 矩阵转置
print(a.reshape(3, -1), 
)  # 只管3行,列数多少自动计算

print("""
------矩阵拼接------

---------按行拼接hstack(元组),按列拼接vstack(元组)------------------------------------------""")
a = numpy.floor(10 * numpy.random.random((2, 2)))
b = numpy.floor(10 * numpy.random.random((2, 2)))
print(a, 
)
print(b, 
)
print(numpy.hstack((a, b)), 
)
print(numpy.vstack((a, b)), 
)

print("""
------矩阵切分------

---------纵切横分hsplit(矩阵,份数/(位置元组)),---横切纵分vsplit(矩阵,份数/(位置元组)),---------------""")
a = numpy.floor(10 * numpy.random.random((2, 12)))
print(a, 
)
print(numpy.hsplit(a, 3), 
)
print(numpy.hsplit(a, (3, 4)))  # 在第三个元素后切一刀,在第四个元素后切一刀
a = numpy.floor(10 * numpy.random.random((12, 2)))
print(a, 
)
print(numpy.vsplit(a, 3))

print("""
------复制问题------

-------------------------------------------指向操作----------------------------------------------------""")
"""
    python中,一切皆对象,a与b指向同一个对象。当命令b去改变对象时,a由于也是指向该对象,所以都会改变。
"""
a = numpy.arange(12)
b = a
print(b is a)
b.shape = (3, 4)
print(a.shape)
print(id(a))
print(id(b))

print("""-----------------------------浅拷贝a.view()----------------------------------------------------""")
"""
    一切皆对象,所以矩阵中的元素也是对象。
    类似于python中的copy.copy(),浅拷贝,只拷贝一层对象,也就是之拷贝矩阵,并不拷贝矩阵中的对象。
"""
c = a.view()
print(c is a)
c.shape = (2, 6)
print(a.shape)
c[0, 4] = 1234
print(a)
print(id(a))
print(id(c))
print("""-----------------------------深拷贝a.copy()----------------------------------------------------""")
"""
    一切皆对象,所以矩阵中的元素也是对象。
    类似于python中的copy.deepcopy(),深拷贝,拷贝所有层次的对象,不止拷贝矩阵,
    还将矩阵中元素所指向的对象也拷贝一份
"""
d = a.copy()
print(d is a)
d[0, 0] = 9999
print(d)
print(a)

print("""
------按行按列取最大值------

---------------------a.argmax(按行axis = 1/按列axis = 0)---------------------------------------------------""")
data = numpy.sin(numpy.arange(20)).reshape(5, 4)
print(data)
ind = data.argmax(axis = 0)  # 每列的最大值,返回一个向量
print(ind)
print(data.shape[0])  # 返回行数
print(data.shape[1])  # 返回列数
data_max = data[ind, range(data.shape[1])]
print(data_max)

print("""
------矩阵扩展------

---------------------a.tile(a,(行,列))---------------------------------------------------""")
a = numpy.arange(0, 40, 10)
print(a)
b = numpy.tile(a, (3, 5))
print(b)

print("""
------元素排序------

-----------a.sort(按行axis = 1/按列axis = 0)---排序索引值numpy.argsort(a)---------------------""")
a = numpy.array([
    [4, 3, 5],
    [1, 2, 1]
])
print(a, 
)
b = numpy.sort(a, axis = 1)
print(b, 
)
a.sort(axis = 1)
print(a, 
)

a = numpy.array([4, 3, 1, 2])
j = numpy.argsort(a)  # 返回排序索引从小到大2310,2号位最小,0号位最大
print(j, 
)
print(a[j])

 

 

运行结果:

D:Pythonpython.exe G:/编程/python/project/TYD/01/01/02/09-14.py

------以矩阵的方式读取数据------

------------genfromtxt函数(‘文件路径‘,delimiter = ‘分隔符‘,dtype = 读取方式)---------------------
<class ‘numpy.ndarray‘>
[[‘name‘ ‘gender‘ ‘age‘ ‘contry‘]
[‘lilei‘ ‘m‘ ‘18‘ ‘cn‘]
[‘hanmeimei‘ ‘f‘ ‘18‘ ‘cn‘]
[‘lucy‘ ‘f‘ ‘19‘ ‘uk‘]
[‘lili‘ ‘f‘ ‘17‘ ‘usa‘]
[‘tom‘ ‘m‘ ‘18‘ ‘uk‘]]

------numpy.array------

------------numpy中最核心的结构------------------------------------------
[ 5 10 15 20]
[[ 5 10 15]
[20 25 30]
[35 40 45]]

------print(numpy对象.shape)------

------------打印矩阵结构(例如2×3,3×3之类)------------------------------------------
(4,)
(2, 3)

------numpy.array结构------

------------内部结构必须相同------------------------------------------
[1 2 3 4]
int32
[1. 2. 3. 4.]
float64
[‘1‘ ‘2‘ ‘3‘ ‘4‘]
<U11

------数据选取------

------------与python一样,通过索引读取数据------------------------------------------
[[‘name‘ ‘gender‘ ‘age‘ ‘contry‘]
[‘lilei‘ ‘m‘ ‘18‘ ‘cn‘]
[‘hanmeimei‘ ‘f‘ ‘18‘ ‘cn‘]
[‘lucy‘ ‘f‘ ‘19‘ ‘uk‘]
[‘lili‘ ‘f‘ ‘17‘ ‘usa‘]
[‘tom‘ ‘m‘ ‘18‘ ‘uk‘]]
hanmeimei的国家是:cn

------切片选取------

------------与python一样,(起始值:终止值:步长)------------------------------------------
[ 5 10 15]
[2 5 8]
[[1 2]
[4 5]
[7 8]]

------numpy判断------

------------判断某个元素是否在矩阵当中------------------------------------------
[False True False False]
[[False True False]
[False False False]
[False False False]]
[10]
[False True False]
[[20 25 30]]
[False False False False]
[ True True False False]
[ 5 10]

------numpy.array类型的改变------

------------astype()函数,数据类型转换------------------------------------------
<U1
[‘1‘ ‘2‘ ‘3‘]
float64
[1. 2. 3.]

------numpy.array求极值的操作------

------------min(),max()函数------------------------------------------
5
20

------numpy.array按行求和,按列求和------

---------sum()方法---参数axis = 1按行,axis = 0按列------------------------------------------
[ 30 75 120]
[60 75 90]

------矩阵变换------

---------造矩阵:arange();矩阵变换:reshape()------------------------------------------
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
(3, 5)
2
int32
15

------初始化矩阵------

---------造0矩阵:zeros((元组表示矩阵行列))方法,创造1矩阵ones()方法------------------------------------------
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
[[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]

[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]]

------序列矩阵------

---------aragne()方法------------------------------------------
[10 15 20 25]

------随机模块------

---------random((元组表示矩阵行列))方法------------------------------------------
[[6 7 3]
[9 3 9]]

------平均间隔矩阵------

---------linspase(起始值,最大值,个数)方法------------------------------------------
[0. 0.05789474 0.11578947 0.17368421 0.23157895 0.28947368
0.34736842 0.40526316 0.46315789 0.52105263 0.57894737 0.63684211
0.69473684 0.75263158 0.81052632 0.86842105 0.92631579 0.98421053
1.04210526 1.1 ]

------向量运算------

---------加减乘方------------------------------------------
[20 30 40 50]
[0 1 2 3]
[20 29 38 47]
[19 28 37 46]
[0 1 4 9]
[ True True False False]

------矩阵乘法------

---------对应位置乘法和点乘------------------------------------------
A矩阵:
[[1 1]
[0 1]]
B矩阵:
[[2 0]
[3 4]]
A*B对应位置相乘:
[[2 0]
[0 4]]
A·B点乘:
[[5 4]
[3 4]]
A·B点乘:
[[5 4]
[3 4]]

------矩阵科学计算------

---------e的幂,平方根------------------------------------------
[0 1 2]
[1. 2.71828183 7.3890561 ]
[0. 1. 1.41421356]

------矩阵操作------

---------向下取整floor(),矩阵转向量ravel(),向量转矩阵a.shape(),矩阵转置a.T-----------------------
矩阵a:
[[8. 2. 5. 7.]
[6. 5. 1. 3.]
[4. 9. 7. 9.]]

[8. 2. 5. 7. 6. 5. 1. 3. 4. 9. 7. 9.]

[[8. 2.]
[5. 7.]
[6. 5.]
[1. 3.]
[4. 9.]
[7. 9.]]

[[8. 5. 6. 1. 4. 7.]
[2. 7. 5. 3. 9. 9.]]

[[8. 2. 5. 7.]
[6. 5. 1. 3.]
[4. 9. 7. 9.]]


------矩阵拼接------

---------按行拼接hstack(元组),按列拼接vstack(元组)------------------------------------------
[[1. 7.]
[3. 7.]]

[[7. 6.]
[3. 6.]]

[[1. 7. 7. 6.]
[3. 7. 3. 6.]]

[[1. 7.]
[3. 7.]
[7. 6.]
[3. 6.]]


------矩阵切分------

---------纵切横分hsplit(矩阵,份数/(位置元组)),---横切纵分vsplit(矩阵,份数/(位置元组)),---------------
[[4. 0. 0. 8. 6. 3. 3. 8. 0. 0. 7. 6.]
[2. 1. 4. 3. 7. 8. 1. 6. 1. 0. 2. 9.]]

[array([[4., 0., 0., 8.],
[2., 1., 4., 3.]]), array([[6., 3., 3., 8.],
[7., 8., 1., 6.]]), array([[0., 0., 7., 6.],
[1., 0., 2., 9.]])]

[array([[4., 0., 0.],
[2., 1., 4.]]), array([[8.],
[3.]]), array([[6., 3., 3., 8., 0., 0., 7., 6.],
[7., 8., 1., 6., 1., 0., 2., 9.]])]
[[2. 8.]
[1. 3.]
[6. 8.]
[5. 4.]
[0. 9.]
[4. 6.]
[3. 6.]
[4. 9.]
[7. 9.]
[7. 6.]
[0. 2.]
[2. 8.]]

[array([[2., 8.],
[1., 3.],
[6., 8.],
[5., 4.]]), array([[0., 9.],
[4., 6.],
[3., 6.],
[4., 9.]]), array([[7., 9.],
[7., 6.],
[0., 2.],
[2., 8.]])]

------复制问题------

-------------------------------------------指向操作----------------------------------------------------
True
(3, 4)
62145264
62145264
-----------------------------浅拷贝a.view()----------------------------------------------------
False
(3, 4)
[[ 0 1 2 3]
[1234 5 6 7]
[ 8 9 10 11]]
62145264
62187344
-----------------------------深拷贝a.copy()----------------------------------------------------
False
[[9999 1 2 3]
[1234 5 6 7]
[ 8 9 10 11]]
[[ 0 1 2 3]
[1234 5 6 7]
[ 8 9 10 11]]

------按行按列取最大值------

---------------------a.argmax(按行axis = 1/按列axis = 0)---------------------------------------------------
[[ 0. 0.84147098 0.90929743 0.14112001]
[-0.7568025 -0.95892427 -0.2794155 0.6569866 ]
[ 0.98935825 0.41211849 -0.54402111 -0.99999021]
[-0.53657292 0.42016704 0.99060736 0.65028784]
[-0.28790332 -0.96139749 -0.75098725 0.14987721]]
[2 0 3 1]
5
4
[0.98935825 0.84147098 0.99060736 0.6569866 ]

------矩阵扩展------

---------------------a.tile(a,(行,列))---------------------------------------------------
[ 0 10 20 30]
[[ 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30]
[ 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30]
[ 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30]]

------元素排序------

-----------a.sort(按行axis = 1/按列axis = 0)---排序索引值numpy.argsort(a)---------------------
[[4 3 5]
[1 2 1]]

[[3 4 5]
[1 1 2]]

[[3 4 5]
[1 1 2]]

[2 3 1 0]

[1 2 3 4]

Process finished with exit code 0
























































































































































































以上是关于科学计算库Numpy基础操作的主要内容,如果未能解决你的问题,请参考以下文章

python的科学计算库都有哪些

Numpy科学计算从放弃到入门

Numpy科学计算库基础知识(Hello,world)

02numpy

Numpy库使用

数据分析:工具篇NumPyNumPy介绍