Lesson · 40 min · Free
Python Arrays & NumPy
Python Arrays & NumPy body { font-family: sans-serif; line-height: 1.6; margin: 20px; } h1, h2 { color: #2c3e50; } pre { background-color: #ecf0f1; padding: 15px; border-radius: 5px; overflow-x: auto; } code { font-famil
Python Arrays & NumPy
Welcome to this lesson on Python arrays and the indispensable NumPy library, crucial tools for any aspiring data scientist, especially in fields like pharmacy and biotechnology where numerical data is paramount. While Python has a built-in data structure called a list that can store collections of items, it's not optimized for numerical operations on large datasets. This is where NumPy shines. NumPy (Numerical Python) provides an array object that is significantly more efficient for storing and manipulating numerical data than standard Python lists, offering performance comparable to C or Fortran. In the context of pharmacy and biotechnology, you'll frequently encounter large datasets such as patient demographics, drug efficacy trial results, genomic sequences, or spectrophotometry readings. Performing mathematical operations (like calculating means, standard deviations, or performing matrix multiplications) on these datasets efficiently is critical. NumPy's arrays are designed precisely for these tasks, offering both speed and a rich set of mathematical functions.
Understanding NumPy Arrays
At its core, a NumPy array is a grid of values, all of the same type, indexed by a tuple of non-negative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension. This homogeneous nature (all elements being of the same data type) is a key factor in NumPy's performance advantage over Python lists, which can store heterogeneous data types. Let's look at a simple example. Imagine you have a series of drug concentration measurements over time. Representing this as a NumPy array allows for rapid calculations. import numpy as np # Creating a 1D NumPy array (vector) of drug concentrations (e.g., mg/L) drug_concentrations = np.array([10.5, 9.8, 8.2, 7.1, 6.5, 5.9]) print("Drug Concentrations Array:", drug_concentrations) print("Type of array:", type(drug_concentrations)) print("Shape of array:", drug_concentrations.shape) print("Data type of elements:", drug_concentrations.dtype) # Basic operations: e.g., calculating the mean concentration mean_concentration = np.mean(drug_concentrations) print("Mean Concentration:", mean_concentration) # Applying a scalar operation to all elements (e.g., converting to micrograms/L) ug_concentrations = drug_concentrations * 1000 print("Concentrations in ug/L:", ug_concentrations) NumPy also excels at handling multi-dimensional data, which is common in scientific experiments. For instance, you might have a 2D array (matrix) representing the results of a high-throughput screening experiment, where rows could be different compounds and columns could be different assays or time points. import numpy as np # Creating a 2D NumPy array (matrix) for experimental results # Rows: Different patient samples (e.g., Patient A, Patient B) # Columns: Measured biomarkers (e.g., Biomarker 1, Biomarker 2, Biomarker 3) patient_biomarkers = np.array([ [120, 85, 3.5], # Patient A data [135, 92, 4.1], # Patient B data [118, 88, 3.9], # Patient C data [140, 95, 4.3] # Patient D data ]) print("Patient Biomarkers Matrix:\n", patient_biomarkers) print("Shape of matrix:", patient_biomarkers.shape) print("Number of dimensions:", patient_biomarkers.ndim) # Accessing elements: e.g., Biomarker 2 for Patient C (index 2, column 1) print("Biomarker 2 for Patient C:", patient_biomarkers[2, 1]) # Slicing: e.g., all biomarker data for Patient B print("All biomarkers for Patient B:", patient_biomarkers[1, :]) # Slicing: e.g., Biomarker 3 data for all patients print("Biomarker 3 for all patients:", patient_biomarkers[:, 2]) # Performing column-wise operations: e.g., mean for each biomarker mean_biomarkers = np.mean(patient_biomarkers, axis=0) # axis=0 for column-wise operation print("Mean values for each biomarker:", mean_biomarkers) The axis parameter in NumPy functions is crucial. axis=0 typically refers to operations along the columns (computing a statistic for each column), while axis=1 refers to operations along the rows (computing a statistic for each row). Understanding this distinction is vital for correctly analyzing multi-dimensional data.
Key Takeaways:
NumPy arrays are the standard for numerical computation in Python, offering significant performance benefits over standard Python lists for large datasets. Arrays are homogeneous, meaning all elements must be of the same data type, which contributes to their efficiency. NumPy supports multi-dimensional arrays, making it ideal for representing matrices, tensors, and other structured scientific data. It provides a rich set of mathematical functions that operate efficiently on entire arrays, eliminating the need for explicit loops in many cases. The .shape attribute tells you the dimensions of an array, and .dtype tells you the data type of its elements. Indexing and slicing work similarly to Python lists but with extensions for multiple dimensions (e.g., array[row, col] ). The axis parameter in NumPy functions allows you to specify whether operations should be performed row-wise or column-wise.
Practice Exercise: Analyzing Drug Efficacy Data
Imagine you are analyzing data from a clinical trial for a new drug. You have recorded the percentage reduction in a specific disease marker for 10 patients at two different time points (Day 7 and Day 14). Create a 2D NumPy array to store this data. Then, perform the following operations: Calculate the average percentage reduction for all patients at Day 7. Calculate the average percentage reduction for all patients at Day 14. Determine the maximum percentage reduction observed across all patients and both time points. Find the patient (row index) who showed the highest percentage reduction at Day 14. Example data (you can use these values or make up your own similar data): # Patient 1: [Day 7, Day 14] # Patient 2: [Day 7, Day 14] # ... # Patient 10: [Day 7, Day 14] data = [ [15.2, 22.1], [18.5, 25.3], [12.1, 19.8], [20.3, 28.7], [16.8, 23.5], [14.5, 21.0], [19.0, 26.5], [17.3, 24.9], [13.9, 20.5], [21.0, 29.1] ]
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 →