How to Remove Specific Elements in a Numpy Array

Summary: The most straightforward way to remove an element at a given index from a NumPy array is to call the function np.delete(array, index) that returns a new array with the element removed. Problem: Given a Numpy Array; how to remove specific elements from the Numpy array? Example: Consider the following Numpy array as shown below: Challenge: How will you … Read more

How to Change Strings to Lowercase in Pandas DataFrame

Problem Formulation Problem: Given a Pandas DataFrame; how to change the strings in the DataFrame to lowercase? Example: Consider the following Pandas DataFrame: Output: Expected Output: When you change a pandas DataFrame string column to lowercase, then the column is returned such that every string in the column is converted and displayed in lowercase while any non-alphabetical … Read more

How to Overwrite the Previous Print to Stdout in Python?

Summary: The most straightforward way to overwrite the previous print to stdout is to set the carriage return (‘\r’) character within the print statement as print(string, end = “\r”). This returns the next stdout line to the beginning of the line without proceeding to the next line. Problem Formulation Problem Definition: How will you overwrite … Read more

How to Print Colored Text in Python?

Summary: To print colored text in Python, you can use: The simple_color package, The ‘\033[1m’ ANSI escape-sequence, The termcolor module, The coloroma package, The colored library, The prompt_toolkit package. A simple, no-library way to print bolded text in Python is to enclose a given string s in the special escape sequence like so: print(“\033[38;5;4m”). We’ll … Read more

How to Add Time Onto a Datetime Object in Python

Problem: Given a datetime.datetime object in Python, is there a way to add time to the given datetime object? Related Question on StackOverflow: Discussion: Adding time to a datetime object in Python should lead to a new datetime object with the updated time information. For example, if you add 5 hours to a datetime object … Read more

How to Print Bold Text in Python?

Summary: To print bold text in Python, you can use: The simple_color package, The ‘\033[1m’ ANSI escape-sequence, The termcolor module, The coloroma package, The prompt_toolkit package. A simple, no-library way to print bolded text in Python is to enclose a given string s in the special escape sequence like so: print(“\033[1m” + s + “\033[0m”). … Read more

How to Suppress Scientific Notation in Python

Summary: Use the string literal syntax f”{number:.nf}” to suppress the scientific notation of a number to its floating-point representation. Problem Formulation: How will you suppress a number represented in scientific notation by default to a floating-point value? Note: Generally, Python represents huge floating-point numbers or very small floating-point numbers in their scientific form. Scientific notation … Read more