{"id":22814252,"url":"https://github.com/devinterview-io/numpy-interview-questions","last_synced_at":"2025-10-30T17:50:01.026Z","repository":{"id":216154689,"uuid":"740600405","full_name":"Devinterview-io/numpy-interview-questions","owner":"Devinterview-io","description":"🟣 NumPy interview questions and answers to help you prepare for your next machine learning and data science interview in 2025.","archived":false,"fork":false,"pushed_at":"2025-05-19T17:02:18.000Z","size":21,"stargazers_count":15,"open_issues_count":0,"forks_count":5,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-19T18:23:37.840Z","etag":null,"topics":["ai-interview-questions","coding-interview-questions","coding-interviews","data-science","data-science-interview","data-science-interview-questions","data-scientist-interview","interview-practice","interview-preparation","machine-learning","machine-learning-and-data-science","machine-learning-interview","machine-learning-interview-questions","numpy","numpy-interview-questions","numpy-questions","numpy-tech-interview","software-engineer-interview","technical-interview-questions"],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Devinterview-io.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-01-08T17:14:54.000Z","updated_at":"2025-05-19T17:02:21.000Z","dependencies_parsed_at":null,"dependency_job_id":"7985e843-d726-4bb8-af49-5d26995edbf0","html_url":"https://github.com/Devinterview-io/numpy-interview-questions","commit_stats":null,"previous_names":["devinterview-io/numpy-interview-questions"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Devinterview-io/numpy-interview-questions","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fnumpy-interview-questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fnumpy-interview-questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fnumpy-interview-questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fnumpy-interview-questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Devinterview-io","download_url":"https://codeload.github.com/Devinterview-io/numpy-interview-questions/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fnumpy-interview-questions/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":281853658,"owners_count":26573095,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-30T02:00:06.501Z","response_time":61,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-interview-questions","coding-interview-questions","coding-interviews","data-science","data-science-interview","data-science-interview-questions","data-scientist-interview","interview-practice","interview-preparation","machine-learning","machine-learning-and-data-science","machine-learning-interview","machine-learning-interview-questions","numpy","numpy-interview-questions","numpy-questions","numpy-tech-interview","software-engineer-interview","technical-interview-questions"],"created_at":"2024-12-12T13:07:52.280Z","updated_at":"2025-10-30T17:50:01.020Z","avatar_url":"https://github.com/Devinterview-io.png","language":null,"readme":"# 70 Common NumPy Interview Questions in 2025\n\n\u003cdiv\u003e\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://devinterview.io/questions/machine-learning-and-data-science/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fmachine-learning-and-data-science-github-img.jpg?alt=media\u0026token=c511359d-cb91-4157-9465-a8e75a0242fe\" alt=\"machine-learning-and-data-science\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n#### You can also find all 70 answers here 👉 [Devinterview.io - NumPy](https://devinterview.io/questions/machine-learning-and-data-science/numpy-interview-questions)\n\n\u003cbr\u003e\n\n## 1. What is _NumPy_, and why is it important in _Machine Learning_?\n\n**NumPy** (Numerical Python) is a fundamental library in Python for numerical computations. It's a versatile tool primarily used for its advanced **multi-dimensional array support**.\n\n### Key Features\n\n- **Task-Specific Modules**: NumPy offers a rich suite of mathematical functions in areas such as linear algebra, Fourier analysis, and random number generation.\n\n- **Performance and Speed**:\n  - Enables vectorized operations.\n  - Many of its core functions are implemented in `C` for optimized performance.\n  - It uses contiguous blocks of memory, providing efficient caching and reducing overhead during processing.\n\n- **Broadcasting**: NumPy allows combining arrays of different shapes during arithmetic operations, facilitating streamlined computation.\n\n- **Linear Algebra**: It provides essential linear algebra operations, including matrix multiplication and decomposition methods.\n\n### NumPy Arrays\n\n- **Homogeneity**: NumPy arrays are homogeneous, meaning they contain elements of the same data type.\n- **Shape Flexibility**: Arrays can be reshaped for specific computations without data duplication.\n- **Simple Storage**: They use efficient memory storage and can be created from regular Python lists.\n\n### Performance Benchmarks\n\n1. **Contiguous Memory**: NumPy arrays ensure that all elements in a multi-dimensional array are stored in contiguous memory blocks, unlike basic Python lists.\n\n2. **No Type Checking**: NumPy arrays are specialized for numerical data, so they don't require dynamic type checks during operations.\n\n3. **Vectorized Computing**: NumPy obviates the need for manual looping, making computations more efficient.\n\n### Code Example: NumPy and Efficiency\n\nHere is the Python code:\n\n```python\n# Using Python Lists\npython_list1 = [1, 2, 3, 4, 5]\npython_list2 = [6, 7, 8, 9, 10]\nresult = [a + b for a, b in zip(python_list1, python_list2)]\n\n# Using NumPy Arrays\nimport numpy as np\nnp_array1 = np.array([1, 2, 3, 4, 5])\nnp_array2 = np.array([6, 7, 8, 9, 10])\nresult = np_array1 + np_array2\n```\nIn the above example, both cases opt for element-wise addition, yet the NumPy version is more concise and efficient.\n\u003cbr\u003e\n\n## 2. Explain how _NumPy arrays_ are different from _Python lists_.\n\n**NumPy arrays** and **Python lists** are both versatile **data structures**, but they have distinct advantages and use-cases that set them apart.\n\n### Key Distinctions\n\n#### Storage Mechanism\n\n- **Lists**: These are general-purpose and can store various data types. Items are often stored contiguously in memory, although the list object itself is an array of references, allowing flexibility in item sizes.\n- **NumPy Arrays**: These are designed for homogeneous data. Elements are stored in a contiguous block of memory, making them more memory-efficient and offering faster element access.\n\n#### Underlying Optimizations\n\n- **Lists**: Are not specialized for numerical operations and tends to be slower for such tasks. They are dynamic in size, allowing for both append and pop.\n- **NumPy Arrays**: Are optimized for numerical computations and provide vectorized operations, which can dramatically improve performance. Array size is fixed upon creation.\n\n### Performance Considerations\n\n- **Memory Efficiency**: NumPy arrays can be more memory-efficient, especially for large datasets, because they don't need to store type information for each individual element.\n- **Element-Wise Operations**: NumPy's vectorized operations can be orders of magnitude faster than traditional Python loops, which are used for element-wise operations on lists.\n- **Size Flexibility**: Lists can grow and shrink dynamically, which may lead to extra overhead. NumPy arrays are more memory-friendly in this regard.\n\n#### Use in Machine Learning\n\n- **Python Lists**: Typically used for general data-handling tasks, such as reading in data before converting it to NumPy arrays.\n- **NumPy Arrays**: The foundational data structure for numerical data in Python. Most numerical computing libraries, including TensorFlow and scikit-learn, work directly with NumPy arrays.\n\u003cbr\u003e\n\n## 3. What are the main _attributes_ of a _NumPy ndarray_?\n\nA NumPy `ndarray` is a multi-dimensional array that offers efficiency in numerical operations. Much of its strength comes from its **resilience with large datasets** and **agility in mathematical computations**.\n\n### Main Attributes\n\n- **Shape**: A tuple representing the size of each dimension.\n- **Data Type (dtype)**: The type of data stored as elements in the array.\n- **Strides**: The number of bytes to \"jump\" in memory to move from one element to the next in each dimension.\n\n### NumPy Examples:\n\n#### Shape Attribute\n\n```python\nimport numpy as np\n\n# 1D Array\nv = np.array([1, 2, 3])\nprint(v.shape)  # Output: (3,)\n\n# 2D Array\nm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m.shape)  # Output: (2, 3)\n```\n\n#### Data Type Attribute\n\n```python\nimport numpy as np\n\narr_int = np.array([1, 2, 3])\nprint(arr_int.dtype)  # Output: int64\n\narr_float = np.array([1.0, 2.5, 3.7])\nprint(arr_float.dtype)  # Output: float64\n```\n\n#### Strides Attribute\n\nThe **strides** attribute defines how many bytes one must move in memory to go to the next element along each dimension of the array. If **`x.strides = (10,1)`**, this means that:\n\n\n- Moving one element in the last dimension, we move **1** byte in memory --- as it is a **float64**.\n- Moving one element in the first dimension, we move **10** bytes in memory.\n\n```python\nimport numpy as np\n\nx = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)\nprint(x.strides)  # Output: (6, 2)\n```\n\u003cbr\u003e\n\n## 4. How do you create a _NumPy array_ from a regular _Python list_?\n\n### Problem Statement\n\nThe task is to create a **NumPy array** from a standard Python list.\n\n### Solution\n\nSeveral routes exist to transform a standard Python list into a NumPy array. Regardless of the method, it's crucial to have the `numpy` package installed.\n\n#### Using `numpy.array()`\n\nThis is the most straightforward method.\n\n#### Implementation\n\nHere, I demonstrate how to convert a basic Python list to a NumPy array with `numpy.array()`. While it works for most cases, be cautious with nested lists as they have significant differences in behavior compared to Python lists.\n\n#### Code\n\nHere's the Python code:\n\n```python\nimport numpy as np\n\npython_list = [1, 2, 3]\n\nnumpy_array = np.array(python_list)\nprint(numpy_array)\n```\n\n#### Output\n\nThe output displays the NumPy array `[1 2 3]`. \n\n#### Using `numpy.asarray()`\n\nThis is another method to convert a Python list into a NumPy array. The difference from `numpy.array()` is primarily in how it handles inputs like other NumPy arrays and nested lists.\n\n#### When to Use `numpy.asarray()`\n\nThe function `numpy.asarray()` is beneficial when you're uncertain whether the input is a NumPy array or a list. It converts non-array types to arrays but leaves already existing NumPy arrays unchanged.\n\n#### Using `numpy.fromiter()`\n\nThis method is useful when you have an iterable and want to create a NumPy array from its elements. An important point to consider is that the iterable is consumed as part of the array-creation process.\n\n#### Using `numpy.arange()` and `numpy.linspace()`\n\nIf your intention is to create sequences of numbers, such as equally spaced data for plotting, NumPy offers specialized methods.\n\n- `numpy.arange(start, stop, step)` generates an array with numbers between `start` and `stop`, using `step` as the increment.\n  \n- `numpy.linspace(start, stop, num)` creates an array with `num` equally spaced elements between `start` and `stop`.\n\u003cbr\u003e\n\n## 5. Explain the concept of _broadcasting_ in _NumPy_.\n\n**Broadcasting** in NumPy is a powerful feature that enables efficient operations on arrays of different shapes without explicit array replication. It works by duplicating the elements along different axes and then carrying out the operation through these 'virtual' repetitions.\n\n### Broadcasting Mechanism\n\n1. **Axes Alignment**: Arrays with fewer dimensions are padded with additional axes on their leading side to match the shape of the other array.\n\n2. **Compatible Dimensions**: For two arrays to be broadcast-compatible, at each axis, their sizes are either equal or one of them is 1.\n\n### Example: Adding Scalars to Arrays\n\nWhen adding a scalar to an array, it's as if the scalar is broadcast to match the shape of the array before the addition:\n\n```python\nimport numpy as np\n\narr = np.array([1, 2, 3])\nscalar = 10\nresult = arr + scalar\n\nprint(result)  # Outputs: [11, 12, 13]\n```\n\n### Visual Representation\n\nThe example below demonstrates what happens at each step of the **three-dimensional** array addition `arr` + `addition_vector`:\n\n```python\nimport numpy as np\n\narr = np.array(\n    [\n        [[1, 2, 3], [4, 5, 6]],\n        [[7, 8, 9], [10, 11, 12]]\n    ]\n)\n\naddition_vector = np.array([1, 10, 100])\nsum_result = arr + addition_vector\n\nprint(f\"Array:\\n{arr}\\n\\nAddition Vector:\\n{addition_vector}\\n\\nResult:\\n{sum_result}\")\n```\n\nThe broadcasting process, along with the output, is visually depicted in the code.\n\n### Real-world Application: Visualizing Multidimensional Data\n\nNumPy broadcasting is invaluable in applications where visualizing or analyzing **multidimensional named data** is essential, permitting easy manipulations without resorting to loops or explicit data copying.\n\nFor instance, matching a three-dimensional RGB image (represented by a 3D NumPy array) with a 1D intensity array prior to modifying the image's pixels is simplified through broadcasting.\n\u003cbr\u003e\n\n## 6. What are the _data types_ supported by _NumPy arrays_?\n\n**NumPy** deals with a variety of data types, which it refers to as **dtypes**.\n\n### NumPy Data Types\n\nNumPy data types build upon the primitive types offered by the machine:\n\n1. **Basic Types**: `int`, `float`, and `bool`.\n   \n2. **Floating Point Types**: `np.float16`, `np.float32`, and `np.float64`.\n\n3. **Complex Numbers**: `np.complex64` and `np.complex128`.\n   \n4. **Integers**: `np.int8`, `np.int16`, `np.int32`, and `np.int64`, along with their unsigned variants.\n   \n5. **Boolean**: Represents `True` or `False`.\n\n6. **Strings**: `np.str_`.\n\n7. **Datetime64**: Date and time data with time zone information.\n\n8. **Object**: Allows any data type.\n   \n9. **Categories and Structured Arrays**: Specialized for categorical data and structured records.\n\n**NumPy** enables you to define arrays with the specific data types:\n\n```python\nimport numpy as np\n\nmy_array = np.array([1, 2, 3])  # Defaults to int64\nfloat_array = np.array([1.5, 2.5, 3.5], dtype=np.float16)\nbool_array = np.array([True, False, True], dtype=np.bool)\n\n# Specifying the dtype of string\nstr_array = np.array(['cat', 'dog', 'elephant'], dtype=np.str_)\n```\n\u003cbr\u003e\n\n## 7. How do you inspect the _shape_ and _size_ of a _NumPy array_?\n\nYou can examine the **shape** and **size** of a NumPy array using two key attributes: `shape` and `size`.\n\n### Code Example: Shape and Size Attributes\n\nHere is the Python code:\n\n```python\nimport numpy as np\n\n# Create a 2D array\narr = np.array([[1, 2, 3], [4, 5, 6]])\n\n# Access shape and size attributes\nshape = arr.shape\nsize = arr.size\n\nprint(\"Shape:\", shape)  # Outputs: (2, 3)\nprint(\"Size:\", size)    # Outputs: 6\n```\n\u003cbr\u003e\n\n## 8. What is the difference between a _deep copy_ and a _shallow copy_ in _NumPy_?\n\nIn NumPy, you can create **shallow** and **deep** copies using the `.copy()` method. \n\nEach type of copy preserves ndarray data in a different way, impacting their link to the original array and potential impact of one on the other.\n\n\n### Shallow Copy\n\nA shallow copy creates a new array object, but it does not duplicate the actual **data**. Instead, it points to the data of the original array. Modifying the shallow copy will affect the original array and vice versa.\n\n\nThe shallow copy is a view of the original array. You can create it either by calling `.copy()` method on an array or using a slice operation.\n\nHere is an example:\n\n```python\nimport numpy as np\n\noriginal = np.array([1, 2, 3])\nshallow = original.copy()\n\n# Modifying the shallow copy\nshallow[0] = 100  # Modifications do not affect the original\nprint(shallow)  # [100, 2, 3]\nprint(original)  # [1, 2, 3]\n\n# Modifying the original\noriginal[1] = 200\nprint(shallow)  # [100, 200, 3]  # The shallow copy is affected\nprint(original)  # [1, 200, 3]\n```\n\n### Deep Copy\n\nA deep copy creates a new array as well as creates separate copies of arrays and their data. **Modifying a deep copy does not affect the original array**, and vice versa.\n\nIn NumPy, you can achieve a deep copy using the same `.copy()` method but with the `order='K'` parameter, or by using `np.array(array, copy=True)`. Here is an example:\n\n```python\nimport numpy as np\n\n# For a 1D array:\noriginal_deep = np.array([1, 2, 3], copy=True)  # This creates a deep copy\noriginal_deep[0] = 100  # Modifications do not affect the original\nprint(original_deep)  # [100, 2, 3]\nprint(original)  # [1, 2, 3]\n\n# For a 2D array:\noriginal_2d = np.array([[1, 2], [3, 4]])\ndeep_2d = original_2d.copy(order='K')  # Deep copy with 'K'\ndeep_2d[0, 0] = 100\nprint(deep_2d)  # [[100, 2], [3, 4]]\nprint(original_2d)  # [[1, 2], [3, 4]]\n\u003cbr\u003e\n\n## 9. How do you perform _element-wise operations_ in _NumPy_?\n\n**Element-wise operations** in NumPy use broadcasting to efficiently apply a single operation to multiple elements in a NumPy array.\n\n### Key Functions\n\n- **Basic Math Functions**: `np.add()`, `np.subtract()`, `np.multiply()`, `np.divide()`, `np.power()`, `np.mod()`\n- **Trigonometric Functions**: `np.sin()`, `np.cos()`, `np.tan()`, `np.arcsin()`, `np.arccos()`, `np.arctan()`\n- **Rounding**: `np.round()`, `np.floor()`, `np.ceil()`, `np.trunc()`\n- **Exponents and Logarithms**: `np.exp()`, `np.log()`, `np.log10()`\n- **Other Elementary Functions**: `np.sqrt()`, `np.cbrt()`, `np.square()`\n- **Absolute and Sign Functions**: `np.abs()`, `np.sign()`\n- **Advanced Array Operations**: `np.dot()`, `np.inner()`, `np.outer()`\n\n### Example: Basic Math Operations\n\nHere is the Python code:\n\n```python\nimport numpy as np\n\n# Generating the arrays\narr1 = np.array([1, 2, 3, 4])\narr2 = np.array([5, 6, 7, 8])\n\n# Element-wise addition\nprint(np.add(arr1, arr2))  # Output: [ 6  8 10 12]\n\n# Element-wise subtraction\nprint(np.subtract(arr1, arr2))  # Output: [-4 -4 -4 -4]\n\n# Element-wise multiplication\nprint(np.multiply(arr1, arr2))  # Output: [ 5 12 21 32]\n\n# Element-wise division\nprint(np.divide(arr2, arr1))  # Output: [5.         3.         2.33333333 2.        ]\n\n# Element-wise power\nprint(np.power(arr1, 2))  # Output: [ 1  4  9 16]\n\n# Element-wise modulo\nprint(np.mod(arr2, arr1))  # Output: [0 0 1 0]\n```\n\u003cbr\u003e\n\n## 10. What are _universal functions_ (_ufuncs_) in _NumPy_?\n\nIn **NumPy**, a **Universal Function** (ufunc) is a function that operates element-wise on **ndarrays**, optimizing performance.\n\nWhether it's a basic arithmetic operation, advanced math function, or a comparison, ufuncs are designed to process data fast.\n\n### Key Features\n\n- **Element-Wise Operation**: Ufuncs process each element in an ndarray individually. This technique reduces the need for explicit loops in Python, leading to enhanced efficiency.\n\n- **Broadcasting**: Ufuncs integrate seamlessly with **NumPy's broadcasting rules**, making them versatile.\n\n- **Code Optimization**: These functions utilize low-level array-oriented operations for optimized execution.\n\n- **Type Conversion**: You can specify the data type for output ndarray, or let NumPy determine the optimal type automatically for you.\n\n- **Multi-Threaded Execution**: Ufuncs are highly compatible with multi-threading to expedite computation.\n\n### Ufunc Categories\n\n1. **Unary Ufuncs**: Operate on a single ndarray.\n   \n   Example: $\\exp(5)$\n\n2. **Binary Ufuncs**: Perform operations between two distinct arrays.\n\n   Example: $10 + \\cos(\\text{{arr1}})$\n\n### Code Example: Unique Advantages of Using Ufuncs\n\n- Ufuncs Empower Faster Computing:\n  - Regex and String Operations: Ufuncs are quicker and more efficient compared to list comprehension and string methods.\n  - Set Operations: Ufuncs enable rapid union, intersection, and set difference with ndarrays.\n\n- Enhanced NumPy Functions:\n  - Log and Exponential Functions: NumPy provides faster and more accurate methods than standard Python math functions.\n  - Trigonometric Functions: Ufuncs are vectorized, offering faster calculations for arrays of angles.\n  - Special Functions: NumPy features an array of special mathematical functions, including Bessel functions and gamma functions, optimized for array computations.\n\n```python\nimport numpy as np\n\narr = np.array([1, 2, 3])\n\n# Using \".prod()\" reduces redundancy and accelerates functional operation.\nresult = arr.prod()\nprint(result)\n\n# Accessing unique elements via ufunc \"np.unique\" is more streamlined and quicker.\nunique_elements = np.unique(arr)\nprint(unique_elements)\n```\n\u003cbr\u003e\n\n## 11. How do you perform _matrix multiplication_ using _NumPy_?\n\n### Problem Statement\n\nThe task is to explain how to perform **matrix multiplication** using **NumPy**.\n\n### Solution\n\nNumPy's `np.dot()` function or the `@` operator is used for both **matrix multiplication** and **dot product**.\n\n#### Matrix Multiplication\n\nTwo matrices are multiplied using the `np.dot()` function.\n\n- $C = A \\times B$ where $A$ is a $2 \\times 3$ matrix and $B$ is a $3 \\times 2$ matrix.\n\n$$\nC = \\begin{bmatrix} A_{11} \u0026 A_{12} \u0026 A_{13} \\\\ A_{21} \u0026 A_{22} \u0026 A_{23} \\end{bmatrix} \\times \\begin{bmatrix} B_{11} \u0026 B_{12} \\\\ B_{21} \u0026 B_{22} \\\\ B_{31} \u0026 B_{32} \\end{bmatrix}\n$$\n\n$$\nC = \\begin{bmatrix} A_{11} \\times B_{11} + A_{12} \\times B_{21} + A_{13} \\times B_{31} \u0026 A_{11} \\times B_{12} + A_{12} \\times B_{22} + A_{13} \\times B_{32} \\\\ A_{21} \\times B_{11} + A_{22} \\times B_{21} + A_{23} \\times B_{31} \u0026 A_{21} \\times B_{12} + A_{22} \\times B_{22} + A_{23} \\times B_{32} \\end{bmatrix}\n$$\n\n#### Broadcasting in NumPy\n\nNumPy has a built-in capability, known as **broadcasting**, for performing operations on arrays of different shapes. If the shapes of two arrays are not compatible for an element-wise operation, NumPy uses broadcasting to make the shapes compatible.\n\n#### Implementation\n\nHere is the Python code using NumPy:\n\n```python\nimport numpy as np\n\nA = np.array([[1, 2, 3], [4, 5, 6]])\nB = np.array([[7, 8], [9, 10], [11, 12]])\n\n# Matrix Multiplication\nC = np.dot(A, B)\n# The result is: [[ 58  64] [139 154]]\n```\n\u003cbr\u003e\n\n## 12. Explain how to _invert a matrix_ in _NumPy_.\n\n### Problem Statement\n\nThe goal is to **invert a matrix** using NumPy.\n\n### Solution\n\nIn NumPy, you can use the `numpy.linalg.inv` function to find the inverse of a matrix.\n\n#### Conditions:\n\n1. The matrix must be square, i.e., it should have an equal number of rows and columns.\n2. The matrix should be non-singular (have a non-zero determinant).\n\n#### Algorithm Steps:\n\n1. Import NumPy: `import numpy as np`\n2. Define the matrix: `A = np.array([[4, 7], [2, 6]])`\n3. Compute the matrix inverse: `A_inv = np.linalg.inv(A)`\n\n#### Implementation\n\nHere's the complete Python code:\n\n```python\nimport numpy as np\n\n# Define the matrix\nA = np.array([[4, 7], [2, 6]])\n\n# Compute the matrix inverse\nA_inv = np.linalg.inv(A)\nprint(A_inv)\n```\n\nThe output for the given matrix `A` is:\n\n```\n[[ 0.6 -0.7]\n [-0.2  0.4]]\n```\n\u003cbr\u003e\n\n## 13. How do you calculate the _determinant_ of a _matrix_?\n\n### Problem Statement\n\nThe **determinant** of a matrix is a scalar value that can be derived from the elements of a **square matrix**.\n\nCalculating the determinant of a matrix is a fundamental operation in linear algebra, with applications in finding the **inverse of a matrix**, solving systems of linear equations, and more.\n\n### Solution\n\n#### Method 1: Numerical Calculation\n\nFor a numeric $n \\times n$ matrix, the determinant is calculated using **Laplace's expansion** along rows or columns. This method is computationally expensive, with a time complexity of $O(n!)$.\n\n#### Method 2: Matrix Decomposition\n\nAn alternative, more efficient approach involves using **matrix decomposition** methods such as **LU decomposition** or **Cholesky decomposition**. However, these methods are more complex and are not commonly used for determinant calculation alone.\n\n#### Method 3: NumPy Function\n\nThe most convenient and efficient method, especially for large matrices, is to make use of the `numpy.linalg.det` function, which internally utilizes LU decomposition.\n\n#### Implementation\n\nHere is Python code:\n\n```python\nimport numpy as np\n\n# Define the matrix\nA = np.array([[1, 2], [3, 4]])\n\n# Calculate the determinant\ndet_A = np.linalg.det(A)\nprint(\"Determinant of A:\", det_A)\n```\n\n#### Output\n\n```\nDeterminant of A: -2.0\n```\n\n### Key Insight\n\nThe determinant of a matrix is crucial in various areas of mathematics and engineering, including linear transformations, volume scaling factors, and the characteristic polynomial of a matrix, often used in Eigenvalues and Eigenvectors calculations.\n\u003cbr\u003e\n\n## 14. What is the use of the `_axis_` parameter in _NumPy functions_?\n\nThe `_axis_` parameter in **NumPy** enables operations to be carried out along a specific axis of a multi-dimensional array, providing more granular control over results.\n\n### Functions with `_axis_` Parameter\n\nMany NumPy functions incorporate the `_axis_` parameter to modify behavior based on the specified axis value.\n\n### Common Functions\n\n- **Math Operations**: Functions such as `mean`, `sum`, `std`, and `min` perform element-wise operations or aggregations, allowing you to focus on specific axes.\n\n- **Array Manipulation**: `concatenate`, `split`, and others enable flexible array operations while considering the specified axis.\n\n- **Numerical Analysis**: Functions like `trapezoid` and `Simpsons` provide integration along a specific axis, especially useful for multi-dimensional datasets.\n  \n### Practical Examples\n\n#### Mean Calculation\n\nSuppose you have the following dataset representing quiz scores:\n\n```python\nimport numpy as np\n\n# Quiz scores for five students across four quizzes\nscores = np.array([[8, 6, 7, 9],\n                   [4, 7, 6, 8],\n                   [3, 5, 9, 2],\n                   [4, 6, 2, 8],\n                   [5, 2, 7, 9]])\n```\n\nYou can calculate the mean scores for each quiz with:\n\n```python\n# axis=0 calculates the mean along the first dimension (students)\nquiz_means = np.mean(scores, axis=0)\n```\n\n#### Splitting Arrays\n\nConsider you want to separate a dataset into two based on a specific criterion. You can do this using `split`:\n\n```python\n# Assign students into two groups based on the mean quiz score\ngroup1, group2 = np.split(scores, [2], axis=1)\n```\n\nIn this case, it splits the `scores` array into two arrays at column index 2, resulting in `group1` containing scores from the first two quizzes and `group2` from the last two quizzes.\n\n#### Integration over Multi-dimensional Arrays\n\nNumPy provides functions to integrate arrays along different axes. For example, using the `trapz` function can calculate the area under the curve represented by the array:\n\n```python\n# Define a 2D array representing a surface\nsurface = np.array([[1, 2, 3, 4],\n                    [2, 3, 4, 5]])\n\n# Perform integration along axis 0\narea_under_curve = np.trapz(surface, axis=0)\n```\n\u003cbr\u003e\n\n## 15. How do you _concatenate_ two _arrays_ in _NumPy_?\n\n### Problem Statement\n\nThe task is to combine two $\\text{NumPy}$ arrays.  Concatenation can occur **horizontally** (column-wise) or **vertically** (row-wise).\n\n### Solution\n\nIn `NumPy`, we can concatenate arrays using the `numpy.concatenate()`, `numpy.hstack()`, or `numpy.vstack()` functions.\n\n#### Key Points\n\n- `numpy.concatenate()`: Combines arrays along a specified **axis**.\n- `numpy.hstack()`: Stacks arrays horizontally.\n- `numpy.vstack()`: Stacks arrays vertically.\n\nLet's explore these methods in more detail.\n\n#### Implementation\n\nHere is the Python code:\n\n```python\nimport numpy as np\n\n# Sample arrays\narr1 = np.array([[1, 2], [3, 4]])\narr2 = np.array([[5, 6], [7, 8]])\n\n# Concatenation along rows (vertically)\nprint(np.concatenate((arr1, arr2), axis=0))  # Output: [[1 2] [3 4] [5 6] [7 8]]\n\n# Concatenation along columns (horizontally)\nprint(np.concatenate((arr1, arr2), axis=1))  # Output: [[1 2 5 6] [3 4 7 8]]\n\n# Stacking horizontally\nprint(np.hstack((arr1, arr2)))  # Output: [[1 2 5 6] [3 4 7 8]]\n\n# Stacking vertically\nprint(np.vstack((arr1, arr2)))  # Output: [[1 2] [3 4] [5 6] [7 8]]\n```\n\u003cbr\u003e\n\n\n\n#### Explore all 70 answers here 👉 [Devinterview.io - NumPy](https://devinterview.io/questions/machine-learning-and-data-science/numpy-interview-questions)\n\n\u003cbr\u003e\n\n\u003ca href=\"https://devinterview.io/questions/machine-learning-and-data-science/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fmachine-learning-and-data-science-github-img.jpg?alt=media\u0026token=c511359d-cb91-4157-9465-a8e75a0242fe\" alt=\"machine-learning-and-data-science\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Fnumpy-interview-questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdevinterview-io%2Fnumpy-interview-questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Fnumpy-interview-questions/lists"}