np.arange()

  1. arr = np.arange(5)
  2. print(repr(arr))
  3. arr = np.arange(5.1)
  4. print(repr(arr))
  5. arr = np.arange(-1, 4)
  6. print(repr(arr))
  7. arr = np.arange(-1.5, 4, 2) #步长
  8. print(repr(arr))

Output:

array([0, 1, 2, 3, 4]) array([0., 1., 2., 3., 4., 5.]) array([-1, 0, 1, 2, 3]) array([-1.5, 0.5, 2.5])

**

np.linspace()

Description: To specify the number of elements in the returned array, rather than the step size, we can use the np.linspace function.

arr = np.linspace(5, 11, num=4)
print(repr(arr))

arr = np.linspace(5, 11, num=4, endpoint=False)
print(repr(arr))

arr = np.linspace(5, 11, num=4, dtype=np.int32)
print(repr(arr))

Output:

array([ 5., 7., 9., 11.]) array([5. , 6.5, 8. , 9.5]) array([ 5, 7, 9, 11], dtype=int32)

np.reshape()

arr = np.arange(8)

reshaped_arr = np.reshape(arr, (2, 4))
print(repr(reshaped_arr))
print('New shape: {}'.format(reshaped_arr.shape))

reshaped_arr = np.reshape(arr, (-1, 2, 2))
print(repr(reshaped_arr))
print('New shape: {}'.format(reshaped_arr.shape))

output:

array([[0, 1, 2, 3], [4, 5, 6, 7]]) New shape: (2, 4) array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) New shape: (2, 2, 2)

flatten()

arr = np.arange(8)
arr = np.reshape(arr, (2, 4))
flattened = arr.flatten()
print(repr(arr))
print('arr shape: {}'.format(arr.shape))
print(repr(flattened))
print('flattened shape: {}'.format(flattened.shape))

Output:

array([[0, 1, 2, 3], [4, 5, 6, 7]]) arr shape: (2, 4) array([0, 1, 2, 3, 4, 5, 6, 7]) flattened shape: (8,)

np.transpose()

arr = np.arange(8)
arr = np.reshape(arr, (4, 2))
transposed = np.transpose(arr)
print(repr(arr))
print('arr shape: {}'.format(arr.shape))
print(repr(transposed))
print('transposed shape: {}'.format(transposed.shape))

Output:

array([[0, 1], [2, 3], [4, 5], [6, 7]]) arr shape: (4, 2) array([[0, 2, 4, 6],

  [1, 3, 5, 7]])

transposed shape: (2, 4)

The code below shows an example usage of the np.transpose function with the axes keyword argument. The shape property gives us the shape of an array.

arr = np.arange(24)
arr = np.reshape(arr, (3, 4, 2))
transposed = np.transpose(arr, axes=(1, 2, 0))
print('arr shape: {}'.format(arr.shape))
print('transposed shape: {}'.format(transposed.shape))

Output:

arr shape: (3, 4, 2)

transposed shape: (4, 2, 3)

np.zeros & np.ones

arr = np.zeros(4)
print(repr(arr))

arr = np.ones((2, 3))
print(repr(arr))

arr = np.ones((2, 3), dtype=np.int32)
print(repr(arr))

np.zeros_like & np.ones_like

arr = np.array([[1, 2], [3, 4]])
print(repr(np.zeros_like(arr)))

arr = np.array([[0., 1.], [1.2, 4.]])
print(repr(np.ones_like(arr)))
print(repr(np.ones_like(arr, dtype=np.int32)))