Python学习之路:NumPy初识
Posted doubest
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习之路:NumPy初识相关的知识,希望对你有一定的参考价值。
import numpy as np;
//一维NumPy数组
myArray = np.array([1,2,3,4]);
print(myArray);
[1 2 3 4]
//打印一维数组的形状
print(myArray.shape);
(4,)
//像普通的Python数组一样,NumPy数组的起始索引编号为0。
print(myArray[0]);
print(myArray[1]);
1
2
//像数组一样直接修改NumPy数组
myArray[0] = 0;
print(myArray[0]);
0
//创建全0或者全1的NumPy数组,默认为浮点数类型
zeroArray = np.zeros((5));
oneArray = np.ones((5));
print(zeroArray);
print(oneArray);
print(type(zeroArray[0]));
[0. 0. 0. 0. 0.]
[1. 1. 1. 1. 1.]
<class 'numpy.float64'>
//创建一个随机值数组
randomArr = np.random.random((5));
print(randomArr);
[0.93867242 0.21884978 0.29078814 0.90407659 0.3323175 ]
//NumPy创建二维数组
dzeroArray = np.zeros((5,4));
doneArray = np.ones((5,4));
print(dzeroArray);
print('----------------');
print(doneArray);
[[0. 0. 0. 0.]
[0. 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.]]
//二维数组依然可以使用一维数组的函数,例如:显示形状、修改元素
testArr = np.ones((5,4));
print(testArr);
print(testArr.shape);
testArr[0,0] = 5
print(testArr);
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
(5, 4)
[[5. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
//提取多维数组的行/列的方法
testArr = np.array([
[1,2],
[3,4]
]);
testArr2 = testArr[:,1]
print(testArr2)
[2 4]
//NumPy矩阵的加减乘除(性质是点运算)
a = np.array([[1.0, 2.0], [3.0, 4.0]])
b = np.array([[5.0, 6.0], [7.0, 8.0]])
sum = a + b
difference = a - b
product = a * b
quotient = a / b
print('sum = \n',sum);
print('difference = \n',difference);
print('product = \n',product);
print('quotient = \n',quotient);
sum =
[[ 6. 8.]
[10. 12.]]
difference =
[[-4. -4.]
[-4. -4.]]
product =
[[ 5. 12.]
[21. 32.]]
quotient =
[[0.2 0.33333333]
[0.42857143 0.5 ]]
//NumPy矩阵的矩阵乘法
realMul = np.dot(a,b);
print(realMul);
print('-----------')
realMul2 = a.dot(b);
print(a,'\n--------\n',b);
print('-----------');
print(realMul2);
[[19. 22.]
[43. 50.]]
-----------
[[1. 2.]
[3. 4.]]
--------
[[5. 6.]
[7. 8.]]
-----------
[[19. 22.]
[43. 50.]]
以上是关于Python学习之路:NumPy初识的主要内容,如果未能解决你的问题,请参考以下文章