task03---数组的操作
1)更改形状
在对数组进行操作时,为了满足格式和计算的要求通常会改变其形状。
`numpy.ndarray.shape`
表示数组的维度,返回一个元组,这个元组的长度就是维度的数目,即 `ndim` 属性(秩)。
import numpy as np
x = np.array([1, 2, 9, 4, 5, 6, 7, 8])
print(x.shape) # (8,)
x.shape = [2, 4]
print(x)
# [[1 2 9 4]
# [5 6 7 8]]
`numpy.ndarray.flat`
将数组转换为一维的迭代器,可以用for访问数组每一个元素。
import numpy as np
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
y = x.flat
print(y)
# <numpy.flatiter object at 0x0000020F9BA10C60>
for i in y:
print(i, end=' ')
# 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
y[3] = 0
print(end='\n')
print(x)
# [[11 12 13 0 15]
# [16 17 18 19 20]
# [21 22 23 24 25]
# [26 27 28 29 30]
# [31 32 33 34 35]]
忽然发现在对x进行.flat函数处理后,y内保存的地址在经过for循环打印输出一次之后无法再次实现打印输出。缘由目前我还不是很清楚。需要向其他大佬请教一下,回头解释。
`numpy.ndarray.flatten([order='C'])`
将数组的副本转换为一维数组,并返回。
- ndarray.flatten(order='C')
- Return a copy of the array collapsed into one dimension.
Parameters: order : {‘C’, ‘F’, ‘A’, ‘K’}, optional
‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.
Returns: A copy of the input array, flattened to one dimension
.
x = np.random.randint(1,100,[5,1,5])
print(x)
y = x.flatten()
print(y)
'''
[[[86 89 92 24 55]]
[[35 75 94 54 92]]
[[51 52 62 92 50]]
[[23 81 77 57 88]]
[[16 69 74 25 9]]]
[86 89 92 24 55 35 75 94 54 92 51 52 62 92 50 23 81 77 57 88 16 69 74 25
9]
'''
y[3] = 0
print(x)
'''
[[[86 89 92 24 55]]
[[35 75 94 54 92]]
[[51 52 62 92 50]]
[[23 81 77 57 88]]
[[16 69 74 25 9]]]
'''
y = x.flatten(order='F')
print(y)
'''
[86 35 51 23 16 89 75 52 81 69 92 94 62 77 74 24 54 92 57 25 55 92 50 88
9]
'''
`numpy.ravel(a, order='C')`
- Return a contiguous flattened array.
- order='C'时返回的是视图;
- order=’F‘ 时是拷贝。
y = x.ravel()
print(y)
y[3] = 0
print(x)
'''
[86 89 92 24 55 35 75 94 54 92 51 52 62 92 50 23 81 77 57 88 16 69 74 25
9]
[[[86 89 92 0 55]]
[[35 75 94 54 92]]
[[51 52 62 92 50]]
[[23 81 77 57 88]]
[[16 69 74 25 9]]]
'''
y = x.ravel(order='