<jupyter_start><jupyter_text>05 ``numpy.array`` 基本操作<jupyter_code>import numpy as np
np.random.seed(0)

x = np.arange(10)
x
X = np.arange(15).reshape((3, 5))
X<jupyter_output><empty_output><jupyter_text>``numpy.array`` 的基本属性<jupyter_code>x.ndim
X.ndim
x.shape
X.shape
x.size
X.size<jupyter_output><empty_output><jupyter_text>``numpy.array`` 的数据访问<jupyter_code>x
x[0]
x[-1]
X
X[0][0] # 不建议！
X[0, 0]<jupyter_output><empty_output><jupyter_text>-1访问最后一个位置元素<jupyter_code>X[0, -1]
x
x[0:5]
x[:5]
x[5:]
x[4:7]
x[::2]
x[1::2]
x[::-1]
X
X[:2, :3]
X[:2][:3] # 结果不一样，在numpy中使用","做多维索引
X[:2, ::2]<jupyter_output><empty_output><jupyter_text>取前两行，步长为2<jupyter_code>X
X[::-1, ::-1]<jupyter_output><empty_output><jupyter_text>行和列都倒着写<jupyter_code>X[0, :]
X[:, 0]<jupyter_output><empty_output><jupyter_text>Subarray of ``numpy.array``<jupyter_code>subX = X[:2, :3]
subX
subX[0, 0] = 100
subX
X<jupyter_output><empty_output><jupyter_text>numpy中修改子矩阵会修改原矩阵，这里使用的是引用传递<jupyter_code>X[0, 0] = 0
X
subX
subX = X[:2, :3].copy()<jupyter_output><empty_output><jupyter_text>copy复制一份出来，防止被修改<jupyter_code>subX[0, 0] = 100
subX
X<jupyter_output><empty_output><jupyter_text>Reshape<jupyter_code>x.shape
x.ndim
x.reshape(2, 5)
x
A = x.reshape(2, 5)
A
x
B = x.reshape(1, 10)
B
B.ndim
B.shape<jupyter_output><empty_output><jupyter_text>维度和shape，既是只有一行，如果指定了reshape为(1,10)也是一个二维数组<jupyter_code>x.reshape(-1, 10)
x.reshape(10, -1)<jupyter_output><empty_output><jupyter_text>-1表示我不管，我就要十行<jupyter_code>x.reshape(2, -1)
x.reshape(5, -1)
x.reshape(3,1)
x.reshape(-1,2)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.19782330345710628, 'fraction_numerical': 0.051856594110115235, 'mean_word_length': 9.705479452054794, 'pattern_counts': {'":': 0, '<': 49, '<?xml version=': 0, '>': 49, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '585983', 'license': 'Apache-2.0', 'n_tokens_mistral': 924, 'n_tokens_neox': 921, 'n_words': 92, 'path': '03-Jupyter-Notebook-Numpy-and-Matplotlib/05-Numpy-Array-Basic-Operations/05-Numpy-Array-Basic-Operations.ipynb', 'repo_name': 'mtianyan/Mtianyan-Play-with-Machine-Learning-Algorithms', 'size': '1562'}