10:32, 7th February 2023
psutil is a cross-platform Python library designed to retrieve information about system resources such as CPU, memory, disk usage and network activity, as well as monitor and manage running processes. It provides functionalities similar to traditional UNIX command-line tools and supports multiple operating systems including Linux, Windows, macOS and various BSD and Solaris variants. Widely adopted by projects such as TensorFlow, PyTorch and Home Assistant, the library is maintained as free software but relies on community and organisational support for ongoing development and maintenance. Security vulnerabilities can be reported through Tidelift and the project encourages contributions and sponsorship to ensure continued reliability and improvement.
10:31, 7th February 2023
The progressbar2 Python library provides a flexible and powerful way to display progress during long-running operations, and can be installed via pip or easy_install. It is built around a ProgressBar class that manages current progress and renders output through a range of customisable widgets, including options for estimated time of arrival, file transfer speed, animated markers, counters, timers and percentage displays.
The library supports multiple usage patterns, such as wrapping iterables, using context managers, handling operations of unknown length and displaying multiple independent progress bars in parallel, including across separate threads. It also supports logging integration, though stderr redirection must be initialised before any stream handlers are set up. Known compatibility limitations exist with the IDLE editor, which does not support this style of progress display, and with Jupyter notebooks, which may require manual flushing of stdout to avoid mixed output.
10:30, 7th February 2023
Python multiprocessing — Process-based parallelism
The multiprocessing module in Python facilitates parallel execution by enabling the creation of separate processes. It provides tools such as Process, Queue and Pool to manage concurrent tasks, along with synchronisation mechanisms like locks and shared memory. Examples demonstrate how to distribute work across multiple processes using queues, handle errors in parallel computations, and utilise pools to execute functions concurrently.
Programming guidelines stress the importance of using freeze_support for compatibility, managing resources carefully and ensuring proper exception handling. The module supports various start methods and contexts, allowing flexibility in how processes are initialised and managed. By following these practices, developers can efficiently leverage multicore processors to improve performance in computationally intensive tasks.
10:29, 7th February 2023
How to Keep Certain Columns in Pandas (With Examples)
In Pandas, there are four main methods for retaining specific columns in a DataFrame. The first involves directly specifying the columns to keep using bracket notation, which suits simple cases where the desired columns are known in advance. The second uses a boolean condition with the isin() function to exclude named columns, effectively keeping everything else. The third employs the drop() method with the axis=1 parameter to remove unwanted columns by name, and is generally favoured for its readability. The fourth uses the filter() method to select columns based on naming patterns, making it particularly useful when working with large datasets that follow consistent column naming conventions.
10:28, 7th February 2023
Python Switch Statement – Switch Case Example
Python introduced a switch-case equivalent through structural pattern matching in version 3.10, allowing developers to replace lengthy if-elif-else chains with a cleaner syntax using match and case keywords. Before this update, programmers relied on functions and conditional statements to simulate switch behaviour, often resulting in repetitive code.
The new approach eliminates the need for explicit break statements, as default cases are handled automatically, streamlining logic for scenarios such as determining career paths based on programming languages. This evolution simplifies handling multiple conditions while maintaining readability, reflecting Python's ongoing efforts to align with common practices in other programming languages.
16:37, 5th February 2023
Python Dictionary Append: How to Add Key/Value Pair
Python dictionaries store data as key-value pairs, with keys being unique and capable of various data types, while values can include lists, numbers, or strings. Keys cannot be duplicated, with the last occurrence taking precedence, and certain structures like lists are disallowed as keys. Elements can be added using the append method for list-based values, updated by directly assigning new values to existing keys, or removed via del, pop, or clear methods. Accessing values requires referencing their keys, and nested dictionaries can be inserted by assigning one dictionary as a value to another key. Examples demonstrate these operations, illustrating how to manage and manipulate dictionary contents effectively.
16:36, 5th February 2023
Concatenate images with Python, Pillow
The Python Imaging Library, Pillow, can be used to combine multiple images both vertically and horizontally by creating a background with Image.new() and pasting images onto it with Image.paste(). When working with images of differing dimensions, there are three main approaches available: cropping the excess area of the larger image, adding coloured margins to fill the space around the smaller image, or resizing one or both images to match before combining.
For resizing, it is generally preferable to scale larger images down rather than enlarging smaller ones, as upscaling degrades image quality. Multiple images can be concatenated at once by passing a list of images through helper functions, and a tiling arrangement can be achieved using a two-dimensional list. When the same image needs to be repeated across a grid, dedicated functions can handle this more efficiently by accepting row and column counts rather than requiring a manually constructed list.
16:35, 5th February 2023
Python PIL | UnsharpMask() method
The Python Imaging Library, known as PIL, offers tools for image manipulation, including the UnsharpMask() method within the ImageFilter module, which enhances image sharpness by applying a blur and contrast adjustment. This method uses parameters such as radius to control the blur intensity, percent to determine the strength of the sharpening effect and threshold to specify the minimum brightness change that contributes to the sharpening process. Example code demonstrates how to apply this filter to an image, adjusting these parameters to achieve different levels of detail enhancement, with visual outputs illustrating the effects of varying the settings.
16:34, 5th February 2023
10 Python Image Manipulation Tools You Can Try Today
Python offers a range of libraries for image processing, enabling tasks such as filtering, enhancement, feature extraction and computer vision applications. Scikit-Image provides research-grade tools with peer-reviewed code, while NumPy and SciPy support array manipulation and advanced image operations. Pillow simplifies common tasks like cropping and colour conversion, and OpenCV-Python delivers high-performance computer vision capabilities. Other libraries such as Mahotas, SimpleITK and PgMagick serve specific needs, from rapid prototyping to handling complex image formats, with varying levels of ease of use and maintenance. These tools collectively provide developers with versatile options for manipulating digital images, whether for basic adjustments or sophisticated analysis.
23:47, 3rd February 2023
Python enumerate(): Simplify Looping With Counters
Exploring Python's enumerate() function reveals its utility in simplifying loops that require both index and value from an iterable. The function pairs each element with its position, eliminating the need to manually track counters. This approach is particularly effective in scenarios like extracting specific segments of a string, linking related lists, or generating sequential pairs.
While enumerate() is powerful, alternatives such as zip() and itertools offer more refined solutions for multi-sequence iteration or complex patterns. Understanding when to use each tool ensures cleaner, more efficient code. The function's flexibility, including the ability to adjust starting indices, makes it a staple in Pythonic programming. By mastering enumerate() and its counterparts, developers can write more readable and maintainable loops tailored to their specific needs.