Lesson · 40 min · Free
NumPy Basics for Data Science
NumPy Basics for Data Science NumPy Basics for Data Science Welcome to the "NumPy Basics for Data Science" lesson, part of our "Python for Data Science" course. In the fields of pharmacy and biotechnology, you'll frequen
NumPy Basics for Data Science
Welcome to the "NumPy Basics for Data Science" lesson, part of our "Python for Data Science" course. In the fields of pharmacy and biotechnology, you'll frequently encounter large datasets – from clinical trial results and genomic sequences to molecular simulation outputs. Efficiently handling and manipulating these numerical data is paramount. This is where NumPy (Numerical Python) comes into play. NumPy is the fundamental package for scientific computing in Python, providing powerful N-dimensional array objects and sophisticated functions for working with these arrays. Unlike standard Python lists, NumPy arrays are designed for numerical operations, offering significant performance advantages for large datasets. This efficiency stems from their homogeneous data type (all elements in a NumPy array must be of the same type) and their underlying implementation in C. For pharmacy and biotech students, this means faster processing of experimental data, more efficient statistical analysis, and the ability to scale your computations without getting bogged down by slow performance.
Understanding NumPy Arrays and Their Advantages
The core of NumPy is its ndarray object. An ndarray (N-dimensional array) is a grid of values, all of the same type, and is indexed by a tuple of non-negative integers. In essence, it's a table of elements (usually numbers), all of the same type, indexed by N dimensions. A 1D array is like a vector, a 2D array is like a matrix, and higher-dimensional arrays are often used for more complex data structures, such as images or volumetric data. The primary advantages of NumPy arrays over Python lists for numerical operations include: Memory Efficiency: NumPy arrays consume less memory than Python lists for storing the same data, especially for large datasets. Performance: Many operations in NumPy are implemented in C or Fortran, leading to significantly faster execution compared to equivalent operations on Python lists. This is crucial when dealing with computationally intensive tasks common in scientific research. Functionality: NumPy provides a vast collection of high-level mathematical functions to operate on arrays, including linear algebra routines, Fourier transforms, and random number generation. Broadcasting: NumPy's broadcasting capabilities allow operations between arrays of different shapes, simplifying code and avoiding explicit loops. Let's start by creating some basic NumPy arrays and performing simple operations. import numpy as np # Creating a 1D array (vector) data_1d = np.array([10, 20, 30, 40, 50]) print("1D Array:", data_1d) print("Type of 1D Array:", type(data_1d)) print("Shape of 1D Array:", data_1d.shape) # (5,) indicates 5 elements in one dimension # Creating a 2D array (matrix) - e.g., representing patient data (rows: patients, columns: metrics) patient_data = np.array([ [65, 120, 1.70], # Patient 1: Age, Weight (lbs), Height (m) [72, 150, 1.85], # Patient 2 [58, 110, 1.62] # Patient 3 ]) print("\n2D Array (Patient Data):\n", patient_data) print("Shape of 2D Array:", patient_data.shape) # (3, 3) indicates 3 rows and 3 columns print("Number of dimensions:", patient_data.ndim) print("Data type of elements:", patient_data.dtype) # Basic arithmetic operations on arrays weights_kg = patient_data[:, 1] * 0.453592 # Convert lbs to kg (1 lb = 0.453592 kg) print("\nPatient Weights in kg:", weights_kg) # Calculate BMI for each patient (Weight (kg) / Height (m)^2) bmi = weights_kg / (patient_data[:, 2] ** 2) print("Patient BMIs:", bmi) As you can see, operations like multiplication and division are applied element-wise across the entire array without needing explicit loops, which is a powerful feature of NumPy. The .shape attribute tells you the dimensions of the array, and .ndim tells you the number of dimensions. The .dtype attribute indicates the data type of the elements within the array, which is crucial for memory management and numerical precision. NumPy also offers many ways to create arrays, such as arrays filled with zeros, ones, or a range of numbers. These are particularly useful for initializing matrices or creating placeholders for data. # Creating arrays with specific values zeros_array = np.zeros((2, 3)) # 2 rows, 3 columns of zeros print("\nArray of Zeros:\n", zeros_array) ones_array = np.ones((3, 2)) # 3 rows, 2 columns of ones print("\nArray of Ones:\n", ones_array) # Creating an array with a range of numbers # np.arange(start, stop, step) - similar to Python's range but returns an array sequence_array = np.arange(0, 10, 2) # Numbers from 0 up to (but not including) 10, with a step of 2 print("\nSequence Array (arange):", sequence_array) # Creating an array with linearly spaced numbers # np.linspace(start, stop, num) - returns 'num' evenly spaced samples over the interval [start, stop] linspace_array = np.linspace(0, 1, 5) # 5 evenly spaced numbers between 0 and 1 (inclusive) print("Linearly Spaced Array (linspace):", linspace_array) # Generating random numbers (useful for simulations or initializations) random_integers = np.random.randint(1, 100, size=(2, 4)) # 2x4 array of random integers between 1 and 99 print("\nRandom Integers:\n", random_integers) random_floats = np.random.rand(3, 3) # 3x3 array of random floats between 0 and 1 print("\nRandom Floats (uniform distribution):\n", random_floats)
Key Takeaways
NumPy's ndarray is the foundational object for scientific computing in Python, offering superior performance and memory efficiency compared to Python lists for numerical data. NumPy arrays are homogeneous, meaning all elements must be of the same data type. NumPy provides powerful capabilities for creating arrays (e.g., np.array() , np.zeros() , np.ones() , np.arange() , np.linspace() , random number generators) and performing element-wise arithmetic operations. The .shape , .ndim , and .dtype attributes are essential for understanding the structure and content of your NumPy arrays. Understanding NumPy is crucial for working with advanced data science libraries like Pandas, SciPy, and Scikit-learn, which are built upon NumPy.
Practice Exercise
Imagine you are analyzing drug efficacy data. You have two arrays: one representing the dosage administered to a group of patients (in mg) and another representing the corresponding reduction in a disease marker (e.g., inflammation score). Create two 1D NumPy arrays: dosages containing values [10, 20, 30, 40, 50] and marker_reduction containing values [2.5, 5.2, 7.8, 10.1, 12.5] . Calculate the 'efficacy per mg' for each dosage ( marker_reduction / dosages ) and print the resulting array. Then, find the average efficacy per mg across all dosages.
Watch the full lesson — free
This topic is part of Python for Data Science, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →