Python NumPy Module: A Comprehensive Overview and Industry Applications

 Pengenalan kepada NumPy

NumPy (Numerical Python) adalah pustaka yang kuat dalam Python untuk komputasi numerik. Ini menyediakan dukungan untuk array dan matriks multidimensi besar, bersama dengan kumpulan fungsi matematika untuk beroperasi pada array ini.

  • Arrays and Array Operations: NumPy memungkinkan pembuatan dan operasi pada array multidimensi.
  • Array Indexing and Slicing: Memungkinkan akses dan manipulasi elemen-elemen tertentu dalam array.
  • Broadcasting and Vectorization: Memungkinkan operasi efisien pada array dengan ukuran berbeda.
  • Mathematical functions and linear algebra: Menyediakan fungsi matematika dan operasi aljabar linier.
  • Array Manipulation and Reshaping: Memungkinkan perubahan bentuk dan struktur array.

  • python
    import numpy as np

    # 1. Arrays and Array Operations
    arr1 = np.array([1, 2, 3, 4, 5])
    arr2 = np.array([6, 7, 8, 9, 10])

    # Basic operations
    sum_arr = arr1 + arr2
    product_arr = arr1 * arr2

    # 2. Array Indexing and Slicing
    matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    element = matrix[1, 1]  # Accessing element at row 1, column 1
    row = matrix[0, :]  # Selecting first row
    column = matrix[:, 2]  # Selecting third column

    # 3. Broadcasting and Vectorization
    scalar = 2
    broadcasted = arr1 * scalar

    # 4. Mathematical functions and linear algebra
    log_arr = np.log(arr1)
    sin_arr = np.sin(arr1)
    dot_product = np.dot(arr1, arr2)

    # 5. Array Manipulation and Reshaping
    reshaped = arr1.reshape(5, 1)
    transposed = matrix.transpose()

    1. Array dan Operasi Array
    Definisi dan Pembuatan Array
    Array: Array NumPy adalah struktur data utama dari pustaka NumPy. Mereka mirip dengan daftar Python tetapi dilengkapi dengan fungsionalitas tambahan untuk menangani dataset besar dan melakukan operasi vektorisasi.
    import numpy as np

    # Creating a 1D array
    arr_1d = np.array([1, 2, 3, 4, 5])

    # Creating a 2D array
    arr_2d = np.array([[1, 2, 3], [4, 5, 6]])

    # Creating an array with a specific data type
    arr_float = np.array([1, 2, 3], dtype=float)


    Operasi Dasar Array
    Operasi Aritmatika: Array NumPy mendukung operasi elemen-demi-elemen, yang berarti operasi diterapkan pada setiap elemen dalam array.
    python
    import numpy as np
    arr = np.array([1, 2, 3, 4, 5])

    # Addition
    arr_add = arr + 2

    # Multiplication
    arr_mult = arr * 2

    # Element-wise operations between two arrays
    arr1 = np.array([1, 2, 3])
    arr2 = np.array([4, 5, 6])
    arr_sum = arr1 + arr2

    2. Indeks Array dan Pemotongan
    Indexing
    Accessing Elements: Anda dapat mengakses elemen dari array NumPy menggunakan indeks.
    #python
    import numpy as np
    arr = np.array([10, 20, 30, 40, 50])

    # Accessing the first element
    first_element = arr[0]

    # Accessing the last element
    last_element = arr[-1]

    Slicing
    Subarray: Pemotongan memungkinkan Anda untuk mengekstrak sebagian dari sebuah array.
    #python
    import numpy as np
    arr = np.array([10, 20, 30, 40, 50])

    # Slicing the first three elements
    slice_1 = arr[0:3]

    # Slicing with a step
    slice_2 = arr[::2]

    3. Broadcasting and Vectorization

    Broadcasting 
    Konsep: Broadcasting adalah mekanisme yang memungkinkan NumPy untuk melakukan operasi pada array dengan bentuk yang berbeda.
    #python
    arr = np.array([1, 2, 3])
    scalar = 2

    # Broadcasting a scalar to an array
    result = arr * scalar  # [2, 4, 6]
    Vectorization
    Komputasi Efisien: Vektorisasi memungkinkan komputasi yang efisien dengan menerapkan operasi pada seluruh array daripada mengiterasi melalui elemen-elemen.
    #python
    import numpy as np
    arr = np.array([1, 2, 3, 4])

    # Vectorized addition
    result = arr + 10  # [11, 12, 13, 14]

    4. Mathematical Functions and Linear Algebra

    Fungsi Matematika
    Operasi Dasar: NumPy menyediakan berbagai fungsi matematika.
    #python
    import numpy as np
    arr = np.array([1, 2, 3])

    # Square root
    sqrt_arr = np.sqrt(arr)

    # Exponential
    exp_arr = np.exp(arr)
    Aljabar Linier
    Operasi Matriks: NumPy memiliki fungsi bawaan untuk melakukan operasi aljabar linier.
    #python
    # Matrix multiplication
    import numpy as np
    matrix1 = np.array([[1, 2], [3, 4]])
    matrix2 = np.array([[5, 6], [7, 8]])
    product = np.dot(matrix1, matrix2)

    # Determinant
    det = np.linalg.det(matrix1)

    5. Array Manipulation and Reshaping
    Manipulation
    Joining and Splitting: nda dapat menggabungkan atau memisahkan array.
    #python
    import numpy as np
    arr1 = np.array([1, 2, 3])
    arr2 = np.array([4, 5, 6])

    # Concatenation
    joined_arr = np.concatenate((arr1, arr2))

    # Splitting
    split_arr = np.split(joined_arr, 2)
    Reshaping
    Reshape: Anda dapat mengubah bentuk array tanpa mengubah data.
    #python
    import numpy as np

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

    # Reshape into a 2x3 array
    reshaped_arr = arr.reshape((2, 3))

    Penjelasan ulang : 
    1. Arrays and Array Operations:

    NumPy memungkinkan pembuatan dan operasi pada array multidimensi dengan efisien. Array NumPy adalah struktur data yang memungkinkan penyimpanan dan manipulasi data numerik dalam bentuk yang terorganisir.

    python
    import numpy as np # Membuat array 1D arr1D = np.array([1, 2, 3, 4, 5]) # Membuat array 2D arr2D = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Operasi aritmatika pada array arr_sum = arr1D + 10 # Menambahkan 10 ke setiap elemen arr_product = arr1D * 2 # Mengalikan setiap elemen dengan 2 # Operasi antar array arr_a = np.array([1, 2, 3]) arr_b = np.array([4, 5, 6]) arr_add = arr_a + arr_b # Penjumlahan elemen-wise arr_mult = arr_a * arr_b # Perkalian elemen-wise print("1D Array:", arr1D) print("2D Array:\n", arr2D) print("Array sum:", arr_sum) print("Array product:", arr_product) print("Array addition:", arr_add) print("Array multiplication:", arr_mult)
    1. Array Indexing and Slicing:

    NumPy menyediakan cara yang fleksibel untuk mengakses dan memanipulasi elemen-elemen tertentu dalam array.

    python
    # Menggunakan array 2D dari sebelumnya print("Original 2D array:\n", arr2D) # Indexing element = arr2D[1, 1] # Mengakses elemen pada baris 1, kolom 1 print("Element at [1, 1]:", element) # Slicing row = arr2D[0, :] # Mengambil seluruh baris pertama column = arr2D[:, 2] # Mengambil seluruh kolom ketiga sub_array = arr2D[0:2, 1:3] # Mengambil sub-array print("First row:", row) print("Third column:", column) print("Sub-array:\n", sub_array) # Conditional indexing greater_than_five = arr2D[arr2D > 5] print("Elements greater than 5:", greater_than_five)
    1. Broadcasting and Vectorization:

    Broadcasting memungkinkan NumPy untuk bekerja dengan array yang memiliki bentuk berbeda, sementara vectorization memungkinkan operasi dilakukan pada seluruh array sekaligus tanpa perlu loop eksplisit.

    python
    import numpy as np # Broadcasting arr_2d = np.array([[1, 2, 3], [4, 5, 6]]) arr_1d = np.array([10, 20, 30]) result = arr_2d + arr_1d # Broadcasting 1D array ke 2D array print("Broadcasting result:\n", result) # Vectorization x = np.array([1, 2, 3, 4]) y = np.array([5, 6, 7, 8]) # Operasi vectorized z = x * y + 2 print("Vectorized operation result:", z) # Bandingkan dengan loop tradisional z_loop = [] for i in range(len(x)): z_loop.append(x[i] * y[i] + 2) print("Traditional loop result:", z_loop)
    1. Mathematical functions and linear algebra:

    NumPy menyediakan berbagai fungsi matematika dan operasi aljabar linier yang dapat diterapkan langsung pada array.

    python
    import numpy as np # Fungsi matematika arr = np.array([0, 30, 45, 60, 90]) sin_arr = np.sin(np.deg2rad(arr)) # Menghitung sinus (dalam radian) log_arr = np.log(np.array([1, 10, 100, 1000])) # Logaritma natural print("Sine of angles:", sin_arr) print("Natural log:", log_arr) # Aljabar linier A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) dot_product = np.dot(A, B) # Perkalian matriks eigenvalues, eigenvectors = np.linalg.eig(A) # Nilai dan vektor eigen print("Matrix dot product:\n", dot_product) print("Eigenvalues:", eigenvalues) print("Eigenvectors:\n", eigenvectors)
    1. Array Manipulation and Reshaping:

    NumPy menyediakan berbagai metode untuk memanipulasi bentuk dan struktur array.

    python
    import numpy as np # Membuat array 1D arr = np.array([1, 2, 3, 4, 5, 6]) # Reshaping reshaped = arr.reshape(2, 3) # Mengubah menjadi array 2D print("Reshaped array:\n", reshaped) # Transposisi transposed = reshaped.T print("Transposed array:\n", transposed) # Stacking arrays arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) vertical_stack = np.vstack((arr1, arr2)) horizontal_stack = np.hstack((arr1, arr2)) print("Vertical stack:\n", vertical_stack) print("Horizontal stack:", horizontal_stack) # Splitting arrays split_arr = np.array([1, 2, 3, 4, 5, 6]) split_result = np.split(split_arr, 3) print("Split result:", split_result)

    Semua fitur ini membuat NumPy sangat kuat untuk manipulasi dan analisis data numerik. Mereka memungkinkan operasi yang efisien pada data berskala besar dan kompleks, yang sangat berguna dalam berbagai aplikasi ilmiah, teknik, dan analisis data.

    6. Practical Implementations in Industry

    implementasi NumPy dalam berbagai industri:

    1. Inventory management:

    python

    import numpy as np
    # Simulasi inventori
    inventory = np.array([100, 150, 200, 80, 120])  # Jumlah item di gudang
    demand = np.array([30, 40, 50, 20, 35])  # Permintaan harian

    # Hitung sisa inventori setelah memenuhi permintaan
    remaining_inventory = inventory - demand

    print("Sisa inventori:", remaining_inventory)

    contoh python
    #python
    import numpy as np

    # Sample stock levels in three warehouses
    stock_levels = np.array([[100, 150, 200], [80, 120, 160], [90, 130, 170]])

    # Calculate the average stock level per warehouse
    avg_stock = np.mean(stock_levels, axis=1)

    # Calculate the total stock across all warehouses
    total_stock = np.sum(stock_levels)
    1. Production planning and optimization
    python
    import numpy as np
    # Simulasi produksi
    production_rates = np.array([10, 15, 20, 12, 18])  # Unit per jam
    hours_worked = np.array([8, 7, 9, 8, 8])  # Jam kerja per hari

    # Hitung total produksi
    total_production = production_rates * hours_worked

    print("Total produksi:", total_production)

    contoh kedua python
    import numpy as np

    # Production resource matrix
    resource_matrix = np.array([[2, 3, 5], [1, 4, 2], [3, 2, 4]])

    # Cost vector
    cost_vector = np.array([50, 30, 40])

    # Calculate total cost for production
    total_cost = np.dot(resource_matrix, cost_vector)


    3. Warehouse and logistics management:
    import numpy as np
    # Simulasi alokasi ruang gudang
    item_volumes = np.array([2, 3, 1.5, 4, 2.5])  # Volume per item (m³)
    item_quantities = np.array([100, 80, 150, 60, 120])  # Jumlah item

    # Hitung total volume yang dibutuhkan
    total_volume = np.dot(item_volumes, item_quantities)

    print("Total volume yang dibutuhkan:", total_volume, "m³")

    contoh python 2
    import numpy as np

    # Distance matrix between warehouses
    distances = np.array([[0, 20, 30], [20, 0, 25], [30, 25, 0]])

    # Calculate the shortest path (this is a simplification)
    shortest_path = np.min(distances, axis=1)

    1. Financial technology (FinTech) solutions
    contoh python 1 :
    import numpy as np
    # Simulasi analisis portofolio
    stock_prices = np.array([100, 150, 200, 120, 180])  # Harga saham
    shares_owned = np.array([50, 30, 20, 40, 25])  # Jumlah saham yang dimiliki

    # Hitung nilai portofolio
    portfolio_value = np.sum(stock_prices * shares_owned)

    print("Nilai portofolio:", portfolio_value)

    contoh python 2 :
    import numpy as np

    # Portfolio returns
    returns = np.array([0.1, 0.05, 0.07, 0.12])

    # Weights of assets in the portfolio
    weights = np.array([0.3, 0.2, 0.2, 0.3])

    # Expected portfolio return
    portfolio_return = np.dot(returns, weights)


    1. Banking and financial services
    contoh python 1 :
    import numpy as np
    # Simulasi perhitungan bunga majemuk
    principal = 10000  # Modal awal
    interest_rate = 0.05  # Suku bunga tahunan
    years = np.array([1, 2, 3, 4, 5])  # Tahun

    # Hitung nilai investasi setelah beberapa tahun
    future_value = principal * (1 + interest_rate) ** years

    print("Nilai investasi setelah beberapa tahun:", future_value)

    contoh python 2 :
    import numpy as np

    # Historical returns
    returns = np.array([-0.02, 0.03, -0.01, 0.04, 0.02])

    # Calculate the 5% Value at Risk (VaR)
    VaR = np.percentile(returns, 5)


    6. E-commerce Platforms
    Customer Behavior Analysis: Analyze customer behavior using vectorized operations.
    import numpy as np

    # Customer purchase amounts
    purchases = np.array([100, 200, 300, 400])

    # Calculate total revenue
    total_revenue = np.sum(purchases)


    7. Insurance and Risk Management
    Claims Analysis: Analyze insurance claims data using NumPy.
    import numpy as np

    # Claims data (claims per month)
    claims = np.array([10, 15, 20, 12, 17])

    # Average claims per month
    avg_claims = np.mean(claims)


    8. Maintenance and Asset Management
    Predictive Maintenance: Use NumPy to track and predict equipment failure.
    import numpy as np

    # Time between failures (in days)
    failures = np.array([30, 45, 60, 50])

    # Predict the next failure using average time between failures
    next_failure = np.mean(failures)


    9. Project Management and Task Automation
    Timeline Analysis: Use NumPy for project timeline and resource analysis.
    import numpy as np

    # Task durations (in days)
    durations = np.array([5, 10, 7, 8])

    # Total project duration
    total_duration = np.sum(durations)


    10. Quality Management and Process Improvement
    Defect Rate Analysis: Analyze defect rates in manufacturing using NumPy.
    import numpy as np

    # Defect rates per batch
    defect_rates = np.array([0.02, 0.03, 0.01, 0.04])

    # Calculate the overall defect rate
    overall_defect_rate = np.mean(defect_rates)


    Comments

    Popular posts from this blog

    create image slider using phyton in web

    Tahukah kamu Algoritma Genetika dan Penerapannya dalam Industri

    create animated futuristic profile card using html+css+js

    CRUD SPRING REACTIVE WEBFLUX +Mongo DB

    Top 7 Digital Transformation Companies

    100 perusahaan perangkat lunak (software) populer dari Eropa dan Amerika yang memiliki kehadiran atau operasional di Indonesia.

    TOP 8 Framework Populer menggunakan bahasa .NET

    Python Date and Time Manipulation

    TOP 5 Trends Programming 2024

    Daftar Kata Kunci (Keyword) dalam Bahasa Pemrograman Python