
Ngân hà ng 200 câu trắc nghiá»m NumPy & pandas
NumPy is the foundational library for scientific computing in Python. Its ndarray object provides fast, memory‑efficient storage of homogeneous data and a rich set of vectorized operations.…

Thuộc tính nào cho biết kích thước theo từng chiều của mảng, ví dụ (3, 4)? •
Giá trị của np.array([[1, 2, 3], [4, 5, 6]]).ndim là: •
Kiểu dữ liệu (dtype) của np.array([1, 2.5, 3]) là: •
Kết quả của np.arange(2, 10, 3) là: •
Kết quả của np.linspace(0, 1, 5) là: •
Lý do chính khiến ndarray tính toán số nhanh hơn list của Python là: •
np.full((2, 3), 7) tạo ra: •
Kết quả của np.arange(6).reshape(2, -1).shape là: •
Cho a = np.array([1, 2, 3]). Kiểu dữ liệu của b = a + 1.5 là: •
Understanding NumPy ndarrays: Core Concepts and Practical Examples
NumPy is the foundational library for scientific computing in Python. Its ndarray object provides fast, memory‑efficient storage of homogeneous data and a rich set of vectorized operations. This course breaks down the most common questions you may encounter in a NumPy & pandas quiz, turning each into a learning opportunity.
1. Creating an ndarray from a Python list
One of the first steps when working with NumPy is converting native Python data structures into an ndarray. The correct syntax is:
np.array([1, 2, 3])
Other functions such as np.list, np.make, or np.vector do not exist in the NumPy API, which is why they are incorrect choices. Using np.array ensures that the resulting object is a homogeneous, contiguous block of memory, enabling the high‑performance calculations NumPy is known for.
2. Inspecting the shape of an ndarray
The .shape attribute returns a tuple describing the size of each dimension. For a two‑dimensional array with three rows and four columns, arr.shape yields (3, 4). This attribute is essential for:
- Validating input dimensions before performing matrix operations.
- Reshaping data to fit machine‑learning models.
- Debugging shape‑mismatch errors that commonly arise in data pipelines.
Other attributes like .ndim (the number of dimensions), .size (total element count), and .dtype (data type) provide complementary information, but only .shape directly answers the question about per‑axis size.
3. Determining the number of dimensions with .ndim
Consider the array created by np.array([[1, 2, 3], [4, 5, 6]]). This is a 2‑by‑3 matrix, meaning it has two axes: rows and columns. Therefore, arr.ndim returns 2. Understanding .ndim helps you:
- Distinguish between vectors (1‑D) and matrices (2‑D).
- Write generic code that works for tensors of arbitrary rank.
4. Data types (dtype) and automatic type promotion
When you create an array with mixed numeric types, NumPy promotes the elements to a common type that can represent all values without loss of precision. For example, np.array([1, 2.5, 3]) results in a float64 dtype because the presence of a floating‑point number forces the whole array to use a floating‑point representation. This automatic promotion ensures consistent arithmetic operations and optimal performance.
5. Generating sequences with np.arange
The function np.arange(start, stop, step) creates an array of evenly spaced values within the half‑open interval [start, stop). For np.arange(2, 10, 3), the sequence starts at 2 and adds the step size 3 until it would exceed 10, producing [2, 5, 8]. This function is analogous to Python’s built‑in range but returns a NumPy array, enabling immediate vectorized operations.
6. Creating linearly spaced arrays with np.linspace
np.linspace(start, stop, num) divides the interval [start, stop] into num equally spaced points, including both endpoints. Calling np.linspace(0, 1, 5) yields [0, 0.25, 0.5, 0.75, 1]. This function is particularly useful for:
- Generating sample points for plotting continuous functions.
- Creating grids for numerical simulations.
7. Why ndarrays are faster than Python lists
The primary performance advantage of ndarray over native Python list stems from two factors:
- Homogeneous data type: All elements share the same
dtype, allowing the interpreter to use a single, low‑level C representation. - Contiguous memory layout: Elements are stored back‑to‑back in a single block of memory, which enables CPU cache‑friendly vectorized operations and SIMD (single instruction, multiple data) optimizations.
In contrast, Python lists store references to separate Python objects, each with its own overhead and potentially different types, which prevents such low‑level optimizations.
8. Initializing arrays with a constant value using np.full
The function np.full(shape, fill_value) creates an array of the specified shape where every element is set to fill_value. For example, np.full((2, 3), 7) produces a 2‑row by 3‑column array where each entry equals 7:
[[7, 7, 7],
[7, 7, 7]]
This is handy for:
- Setting up bias terms in neural‑network layers.
- Creating placeholder matrices before filling them with computed values.
9. Putting it all together: A mini‑project
To reinforce the concepts, let’s build a small data‑processing pipeline that demonstrates array creation, reshaping, and basic arithmetic.
import numpy as np
# 1. Create a 1‑D array from a Python list
vec = np.array([1, 2, 3, 4, 5])
# 2. Generate a range of values using arange
range_arr = np.arange(10, 20, 2) # [10, 12, 14, 16, 18]
# 3. Combine both arrays into a 2‑D array
combined = np.vstack([vec, range_arr])
print('Combined shape:', combined.shape) # (2, 5)
# 4. Change dtype to float for precise division
float_arr = combined.astype(float)
# 5. Perform element‑wise division
result = float_arr / np.full(float_arr.shape, 2)
print('Result:\n', result)
Running this script will output a 2‑by‑5 matrix of floats, each equal to the original value divided by 2. Notice how the .shape, .astype, and np.full functions work together seamlessly.
10. Frequently asked questions (FAQ)
- Can I change the dtype of an existing ndarray? Yes, using the
.astype(new_dtype)method, which returns a copy with the desired type. - What is the difference between
np.arangeandnp.linspace?arangeuses a step size, whilelinspacespecifies the number of points.linspaceguarantees inclusion of the endpoint. - How do I reshape an array without copying data? Use the
.reshape(new_shape)method; it returns a view whenever possible. - Is
np.fullthe only way to create constant arrays? No, you can also usenp.ones,np.zeros, or multiplynp.emptyby a scalar, butnp.fullis the most explicit for arbitrary constants.
11. SEO‑friendly recap
By mastering the fundamentals covered in this course—array creation with np.array, shape inspection via .shape, dimension counting with .ndim, dtype handling, sequence generation using np.arange and np.linspace, performance benefits of contiguous memory, and constant initialization with np.full—you’ll be well‑prepared for both quizzes and real‑world data‑science tasks. Incorporate these keywords (NumPy ndarray, np.array, np.arange, np.linspace, np.full, dtype, shape, ndim) into your study notes and online profiles to improve discoverability for recruiters and search engines alike.
