Lesson · 40 min · Free
Python Arrays with NumPy
Python Arrays with NumPy body { font-family: sans-serif; line-height: 1.6; margin: 20px; } h1, h2 { color: #2c3e50; } pre, code { background-color: #ecf0f1; padding: 10px; border-radius: 5px; overflow-x: auto; } ul { lis
Python Arrays with NumPy
Welcome to this lesson on Python Arrays with NumPy, a foundational topic for anyone delving into data science with Python, especially within the pharmacy and biotechnology sectors. While Python's built-in lists are versatile, they have limitations when dealing with large datasets and performing numerical operations efficiently. This is where NumPy (Numerical Python) comes in. NumPy provides a powerful array object, the ndarray , which is significantly faster and more memory-efficient than Python lists for numerical computations. In pharmaceutical research, you might be analyzing large datasets of patient demographics, drug efficacy trials, genomic sequences, or molecular structures. NumPy arrays are optimized for these kinds of tasks, allowing you to perform vectorized operations – applying an operation to an entire array at once without explicit loops – which drastically speeds up computation. This efficiency is crucial when working with the massive datasets common in biotech and clinical trials.
Understanding NumPy Arrays (ndarray)
A NumPy array is a grid of values, all of the same data type, and is indexed by a tuple of non-negative integers. The number of dimensions is the array's rank , and the shape of an array is a tuple of integers giving the size of the array along each dimension. Unlike Python lists, which can hold elements of different data types, NumPy arrays enforce a single data type, leading to contiguous memory allocation and faster access. Let's look at how to create and manipulate NumPy arrays. First, you'll need to import the NumPy library, conventionally aliased as np . import numpy as np # Creating a 1-dimensional array (vector) data_points = np.array([10.5, 12.3, 11.8, 13.1, 10.9]) print("1D Array (Vector):", data_points) print("Type of data_points:", type(data_points)) print("Shape of data_points:", data_points.shape) print("Data type of elements:", data_points.dtype) # Creating a 2-dimensional array (matrix) - e.g., patient vital signs over time patient_vitals = np.array([ [72, 120, 80], [75, 122, 82], [70, 118, 78], [73, 121, 81] ]) print("\n2D Array (Matrix - Patient Vitals):\n", patient_vitals) print("Shape of patient_vitals:", patient_vitals.shape) print("Number of dimensions:", patient_vitals.ndim) In the example above, patient_vitals could represent, for instance, heart rate, systolic blood pressure, and diastolic blood pressure for four different patients or four different time points for a single patient. The .shape attribute tells us the dimensions (4 rows, 3 columns), and .ndim tells us it's a 2-dimensional array. One of the most powerful features of NumPy is its ability to perform element-wise operations and vectorized computations. This means you can apply mathematical functions to entire arrays without writing explicit loops, which is both more concise and significantly faster. import numpy as np # Example: Drug concentration measurements (in mg/L) drug_concentrations = np.array([5.2, 5.5, 5.1, 5.8, 5.3]) # Add a constant value (e.g., correcting for a baseline error of 0.1 mg/L) corrected_concentrations = drug_concentrations + 0.1 print("Corrected concentrations:", corrected_concentrations) # Multiply by a scalar (e.g., converting to grams/L by dividing by 1000, then multiplying by 100 for % concentration) percent_concentration = (drug_concentrations / 1000) * 100 print("Percent concentration:", percent_concentration) # Element-wise operations between two arrays (e.g., subtracting placebo effect) placebo_effect = np.array([0.2, 0.3, 0.1, 0.4, 0.2]) net_effect = drug_concentrations - placebo_effect print("Net effect (drug - placebo):", net_effect) # Applying a mathematical function (e.g., calculating the natural logarithm of concentrations) import math log_concentrations = np.log(drug_concentrations) # NumPy's log function is element-wise print("Natural log of concentrations:", log_concentrations) # Calculating statistics mean_concentration = np.mean(drug_concentrations) std_dev_concentration = np.std(drug_concentrations) print(f"Mean concentration: {mean_concentration:.2f} mg/L") print(f"Standard deviation: {std_dev_concentration:.2f} mg/L") Notice how straightforward it is to perform complex operations. The np.log() function, for instance, automatically applies the logarithm to each element of the array. This vectorized approach is what makes NumPy indispensable for numerical computing in Python, especially in fields like pharmacokinetics and pharmacodynamics where statistical analysis of large datasets is routine.
Key Takeaways
NumPy provides the ndarray object, a powerful and efficient array for numerical operations. NumPy arrays are faster and more memory-efficient than Python lists for numerical data. All elements in a NumPy array must have the same data type. Vectorized operations allow applying functions and arithmetic operations to entire arrays without explicit loops, significantly improving performance. NumPy is essential for scientific computing, data analysis, and machine learning in Python, particularly in pharmacy and biotech for handling large experimental datasets.
Practice Exercise
Imagine you have measured the efficacy of a new drug in two different patient cohorts. The efficacy is measured as a percentage improvement. Cohort A showed improvements of [15.2, 17.5, 16.0, 18.1, 16.8] , and Cohort B showed improvements of [14.8, 16.9, 15.5, 17.7, 16.3] . Using NumPy, calculate the following: Create two NumPy arrays, cohort_a and cohort_b , from these lists. Calculate the average improvement for each cohort. Calculate the difference in improvement between Cohort A and Cohort B for each patient pair (assuming they are matched). Determine the overall mean improvement across both cohorts combined.
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 →