Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Perform Array Manipulation Using NumPy in Python

Array Manipulation Using NumPy

Condition for Array Manipulation Using NumPy in Python

  • Description:
    NumPy is a powerful library in Python used for numerical computations and provides support for large, multi-dimensional arrays and matrices.

    Array manipulation refers to operations that modify or access elements, change the shape, and perform mathematical operations on arrays.
Step-by-Step Process
  • Import NumPy:
    Import the NumPy library.
  • Create an Array:
    Use numpy.array() to create arrays or other functions like numpy.arange(), numpy.zeros(), numpy.ones(), and numpy.linspace() for specific needs.
  • Array Indexing and Slicing:
    Use slicing and indexing to access or modify elements in the array.
  • Reshaping Arrays:
    Use functions like reshape(), flatten(), and transpose() to modify the shape of the array.
  • Element-wise Operations:
    Perform mathematical operations on arrays, such as addition, multiplication, or applying a function element-wise.
  • Concatenation and Splitting:
    Use concatenate(), hstack(), vstack() to join arrays, and split() to divide arrays.
  • Broadcasting:
    Perform operations between arrays of different shapes.
Sample Source Code
  • # Code for array manipulation

    import numpy as np

    arr = np.array([1, 2, 3, 4, 5])

    print("Original Array:", arr)

    # Accessing an element by index
    print("\nElement at index 2:", arr[2])

    # Slicing the array
    print("\nSliced Array (from index 1 to 3):", arr[1:4])

    # Reshaping Arrays
    arr_2d = arr.reshape(1, -1) # Reshape to 2D
    print("\nReshaped Array (1 row, 5 columns):\n", arr_2d)

    # Flattening the array (Converting 2D to 1D)
    flattened_arr = arr_2d.flatten()
    print("\nFlattened Array:", flattened_arr)

    # Element-wise Operations
    arr_add = arr + 10 # Add 10 to each element
    print("\nArray after adding 10:", arr_add)

    arr_multiply = arr * 2 # Multiply each element by 2
    print("\nArray after multiplying by 2:", arr_multiply)

    arr_square = np.square(arr) # Square each element
    print("\nArray after squaring elements:", arr_square)

    # Concatenation
    arr2 = np.array([6, 7, 8])
    concatenated_arr = np.concatenate((arr, arr2))
    print("\nConcatenated Array:", concatenated_arr)

    # Array Splitting
    split_arr = np.split(arr, 5) # Split array into 5 parts
    print("\nArray Split into 5 parts:", split_arr)

    # Broadcasting (Adding a scalar to an array)
    broadcasted_arr = arr + 3 # Add 3 to each element
    print("\nArray after broadcasting with 3:", broadcasted_arr)
Screenshots
  • Array Manipulation Using NumPy