Lesson · 40 min · Free
Python Casting Basics
Python Casting Basics 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 Casting Basics
Welcome to this module on Python Casting Basics , a fundamental concept in programming that is particularly relevant when working with diverse data types in data science, especially within pharmacy and biotechnology contexts. In data analysis, you'll frequently encounter data from various sources – patient records, lab results, experimental measurements, genomic sequences – which might be stored or interpreted in different formats. Understanding how to convert data from one type to another, known as "casting," is crucial for data cleaning, manipulation, and ensuring your analyses are performed correctly. Python is a dynamically typed language, meaning you don't explicitly declare the data type of a variable when you create it. Python infers the type based on the value assigned. However, there are many scenarios where you need to explicitly change a variable's data type. For instance, if you read a numerical value from a CSV file, it might be interpreted as a string, but you'll need to convert it to an integer or a float to perform mathematical calculations. Similarly, you might need to convert a boolean value (True/False) into an integer (1/0) for certain statistical models or to convert a list of drug IDs into a set to find unique entries efficiently.
Understanding Explicit Type Conversion (Casting)
Casting in Python refers to the process of converting a variable from one data type to another. This is done using built-in functions that correspond to the desired data type. The most common casting functions you will use are int() , float() , str() , bool() , list() , tuple() , and set() . It's important to remember that not all conversions are possible or make logical sense (e.g., converting a non-numeric string like "hello" to an integer will result in an error). Python will raise a ValueError if an invalid conversion is attempted. Let's look at some practical examples that you might encounter in a biotech or pharmacy setting.
Example 1: Numerical and String Conversions
Imagine you have patient IDs that are sometimes treated as numbers and sometimes as strings, or lab values that are read as strings but need to be floats for calculations. # Scenario: Patient IDs and Lab Values # Patient ID read as a string from a database patient_id_str = "1002345" print(f"Original Patient ID (string): {patient_id_str}, Type: {type(patient_id_str)}") # Convert string ID to integer for numerical operations (e.g., comparison, sorting) patient_id_int = int(patient_id_str) print(f"Converted Patient ID (integer): {patient_id_int}, Type: {type(patient_id_int)}") # Lab result (e.g., glucose level) read as a string glucose_level_str = "98.5" print(f"\nOriginal Glucose Level (string): {glucose_level_str}, Type: {type(glucose_level_str)}") # Convert string glucose level to float for calculations glucose_level_float = float(glucose_level_str) print(f"Converted Glucose Level (float): {glucose_level_float}, Type: {type(glucose_level_float)}") # Perform a calculation threshold = 100.0 if glucose_level_float > threshold: print("Glucose level is above threshold.") else: print("Glucose level is within normal range.") # Convert a number back to a string for display or concatenation drug_concentration = 0.75 # mg/mL report_string = "The drug concentration is " + str(drug_concentration) + " mg/mL." print(f"\nReport String: {report_string}")
Example 2: Boolean and Collection Conversions
In clinical trials, you might have boolean flags for patient eligibility or lists of adverse events that need to be processed efficiently. # Scenario: Patient Eligibility and Adverse Events # Patient eligibility flag (1 for eligible, 0 for not eligible) is_eligible_int = 1 print(f"Original Eligibility (integer): {is_eligible_int}, Type: {type(is_eligible_int)}") # Convert integer to boolean for logical checks is_eligible_bool = bool(is_eligible_int) print(f"Converted Eligibility (boolean): {is_eligible_bool}, Type: {type(is_eligible_bool)}") # Note: 0 converts to False, any non-zero number converts to True is_not_eligible_int = 0 is_not_eligible_bool = bool(is_not_eligible_int) print(f"Converted (0) Eligibility (boolean): {is_not_eligible_bool}, Type: {type(is_not_eligible_bool)}") # List of adverse events reported for a drug adverse_events_list = ["nausea", "headache", "fatigue", "nausea", "dizziness"] print(f"\nOriginal Adverse Events (list): {adverse_events_list}") # Convert list to a set to find unique adverse events unique_adverse_events = set(adverse_events_list) print(f"Unique Adverse Events (set): {unique_adverse_events}, Type: {type(unique_adverse_events)}") # Convert back to a list if ordered access or duplicates are needed later unique_adverse_events_list = list(unique_adverse_events) print(f"Unique Adverse Events (list again): {unique_adverse_events_list}, Type: {type(unique_adverse_events_list)}") # Convert a string into a list of characters gene_sequence = "ATGCGT" sequence_chars = list(gene_sequence) print(f"\nGene Sequence as List of Chars: {sequence_chars}") As you can see, casting allows you to flexibly work with your data, transforming it into the most suitable type for the task at hand. This flexibility is a powerful tool in data science, enabling robust data cleaning, validation, and analysis workflows.
Key Takeaways:
Casting is the explicit conversion of a variable from one data type to another. Common casting functions include int() , float() , str() , bool() , list() , tuple() , and set() . Casting is essential for data cleaning , data validation , and ensuring correct mathematical or logical operations . Attempting an impossible conversion (e.g., int("hello") ) will raise a ValueError . In pharmacy/biotech, casting is vital for handling diverse data like patient IDs, lab results, and experimental parameters.
Practice Exercise:
You are given a dataset where drug dosages are sometimes recorded as strings with units and sometimes as pure numbers. For a specific analysis, you need all dosages to be numerical (float type) and then categorize them as "High" (>= 100 mg), "Medium" (>= 50 mg and dosages = ["25 mg", "120 mg", "75", "48.5 mg", "150", "30.0"] . Your code should convert each dosage to a float, remove any units if present, and then print the dosage along with its category.
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 →