1、numpy中变换元素的类型
numbers = numpy.array(['1', '2', '3'])
print(numbers.dtype)
print(numbers)
numbers = numbers.astype(float)
print(numbers.dtype)
print(numbers)
#运行结果:
<U1
['1' '2' '3']
float64
[1. 2. 3.]
OK,通过dtype方法我们可以看到,最初的时候,我们传入的数组中,元素类型为str,通过astype()属性,我们可以将元素的类型进行转换。
2、取数组中的极值操作
vector = numpy.array([5, 10, 15, 20])
print(vector.min())
print(vector.max())
#运行结果:
5
20
通过min()和max()方法来求数组中的最大值和最小值。
3、按行求和或按列求和
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
print(matrix.sum(axis=1))
#运行结果:
[ 30 75 120]
我们可以看出来5+10+15=30, 20+25+30=75,35+40+45=120。好像是对每一行进行了相加。我们再看下面的代码:
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
print(matrix.sum(axis=0))
#运行结果:
[60 75 90]
我们可以看下,5+20+35=60, 10+25+40=75, 15+30+45=90。嗯,刚好等于每一列的和。
上述代码中,axis代表了一个维度,axis=1代表行,axis=0代表列
4、对numpy中的矩阵进行变换
import numpy as np
print(np.arange(15))
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape)
#运行结果:
[ 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)
采用np.arange()方法,则生成一个0-14的数组。使用reshape()方法将数组变为矩阵,reshape(3,5)代表变为3行5列。
我们可以通过shape方法可以看出,该矩阵为3行5列。
5、ndim & dtype.name & size属性
a = np.arange(15).reshape(3, 5)
print(a.ndim)
#运行结果:
2
通过a.ndim查取数组的维度。
a = np.arange(15).reshape(3, 5)
print(a.dtype.name)
#运行结果:
int32
通过a.dtype.name获得元素的类型。
a = np.arange(15).reshape(3, 5)
print(a.size)
#运行结果:
15
通过a.size获得元素的个数。
6、获得元素为0或者1的矩阵
a = np.zeros((3, 4))
print(a)
#运行结果:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
通过np.zeros((3,4))获得一个3行4列的矩阵,矩阵中每个元素都为0。特别要注意的是,传入np.zeros()中的是(3,4)的元组,不能直接将3,4传进去,不然会报错。
a = np.ones((2, 3, 4))
print(a)
#运行结果
[[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]]
同理,我们用np.ones()可以构造一个值全部是1的矩阵。(2,3,4)说明这个矩阵是三维的。
但是我们发现,为什么1后面有个小数点呢?其实,我们还可以将np.ones()再优化一下,确认元素的类型,比如:
a = np.ones((2, 3, 4), dtype=int)
print(a)
#运行结果:
[[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]]
果然,运行结果就没有小数点了。