Numpy 入门
参考资料:https://numpy.org/doc/stable/user/absolute_beginners.html
-
Convert a 1D array into a 2D array
You can use np.newaxis and np.expand_dims to increase the dimensions of your existing array.
-
np.newaxisIncrease the ddimensions of your array by one dimension.(1D->2D, 2D->3d…)a = np.array([1,2,3,4])a.shape(6,)a2 = a[np.newaxis, :]a2array([[1,2,3,4]])a3 = a[:, np.newaxis]a3array([[1],[2],[3],[4],[5],[6]]) -
np.expand_dimsepand an array by inserting a new axis at a specified positiona = np.array([1,2,3,4])b = np.expand_dims(a, axis=1)b.shape(4, 1)c = np.expand_dims(a, aixs=0)c.shape(1, 4)
- Indexing and Slicing You can index and slice NumPy arrays in the same ways you can slice Python lists
-
np.nonzeros()a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])b = np.nonzero(a < 5)print(b)(array([0, 0, 0, 0]), array([0, 1, 2, 3]))In this example, a tuple of arrays was returned: each array represents a dimension, for instance, the first array shows the row indices where these values are found.
You can also use np.nonzero() to print the elements in an array that are less than 5 with:
print(a[b])
- Create an array from existing data
You can also stack two existing arrays, both vertically and horizontally.
a1 = np.array([[1, 1],[2, 2]])a2 = np.array([[3, 3],[4, 4]])
-
vstacknp.vstack((a1, a2))array([[1, 1],[2, 2],[3, 3],[4, 4]]) -
hstacknp.hstack((a1, a2))array([[1, 1, 3, 3],[2, 2, 4, 4]])
-
Dtype There can only be one type in an array, and we can get the exact type by calling
dtype -
How to save and load NumPy objects This is the main reason why I write this note. Study this to finish my Python homework.
The ndarray objects can be saved to and loaded from the disk files with
loadtxtandsavetxtfunctions that handle normal text files, load and save functions that handle NumPy binary files with a .npt file extension, and asavezfunction that handles NumPy files with a .npz file extension.If you want to store a single ndarray object, store it as a .npy file using
np.save. If you want to store more than one ndarray object in a single file, save it as a .npz file usingnp.savez. You can also save several arrays into a single file in compressed npz format with savez_compressed.It’s easy to save and load an array with np.save(). Just make sure to specify the array you want to save and a file name.
a = np.array([1,2,3,4,5,6])np.save('filename', a)b = np.load('filename.npy')print(b)[1,2,3,4,5,6]You can save a Numpy array as a plain text file like a .csv or .txt file with
np.savetxtcsv_arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])np.savetxt('new_file.csv', csv_arr)np.loadtxt('new_file.csv')array([1., 2., 3., 4., 5., 6., 7., 8.])