Articles on Trending Technologies

Technical articles with clear explanations and examples

Python – Stacking a single-level column with Pandas stack()?

AmitDiwan
AmitDiwan
Updated on 26-Mar-2026 587 Views

The Pandas stack() method transforms a DataFrame by stacking column levels into row levels, creating a hierarchical index. This operation pivots columns into a multi-level index, converting wide data to long format. Syntax DataFrame.stack(level=-1, dropna=True) Creating a DataFrame with Single-Level Columns First, let's create a simple DataFrame with single-level columns ? import pandas as pd # Create DataFrame with single-level columns dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]], ...

Read More

Python - Create nested list containing values as the count of list items

AmitDiwan
AmitDiwan
Updated on 26-Mar-2026 280 Views

When it is required to create a nested list containing values as the count of list elements, a simple iteration and list comprehension can be used. This technique replaces each element with a list containing repeated values based on the element's position. Example Below is a demonstration of creating nested lists where each position contains a list with repeated values ? my_list = [11, 25, 36, 24] print("The original list is:") print(my_list) for element in range(len(my_list)): my_list[element] = [element + 1 for j in range(element + 1)] print("The resultant nested ...

Read More

Python - Count the frequency of matrix row length

AmitDiwan
AmitDiwan
Updated on 26-Mar-2026 255 Views

When working with matrices (lists of lists), you may need to count how many rows have the same length. Python provides several approaches to count the frequency of matrix row lengths using dictionaries or the Counter class. Using Dictionary with Manual Counting The traditional approach iterates through the matrix and manually tracks row length frequencies ? matrix = [[42, 24, 11], [67, 18], [20], [54, 10, 25], [45, 99]] print("The matrix is:") print(matrix) frequency = {} for row in matrix: length = len(row) if length not ...

Read More

Python - How to rename multiple column headers in a Pandas DataFrame with Dictionary?

AmitDiwan
AmitDiwan
Updated on 26-Mar-2026 858 Views

In Pandas, you can rename multiple column headers simultaneously using the rename() method with a dictionary. The dictionary maps old column names (keys) to new column names (values). Syntax DataFrame.rename(columns=dictionary, inplace=True) Where dictionary contains old_name: new_name pairs, and inplace=True modifies the original DataFrame. Creating a Sample DataFrame Let's start by creating a DataFrame with car data ? import pandas as pd dataFrame = pd.DataFrame({ "Car": ['BMW', 'Mustang', 'Tesla', 'Mustang', 'Mercedes', 'Tesla', 'Audi'], "Cubic Capacity": [2000, 1800, 1500, 2500, 2200, 3000, 2000], ...

Read More

Python - Select columns with specific datatypes

AmitDiwan
AmitDiwan
Updated on 26-Mar-2026 265 Views

To select columns with specific datatypes in Pandas, use the select_dtypes() method with the include parameter. This method allows you to filter DataFrame columns based on their data types such as object, int64, float64, etc. Syntax DataFrame.select_dtypes(include=None, exclude=None) Parameters include − List of data types to include exclude − List of data types to exclude Creating a Sample DataFrame Let's start by creating a DataFrame with different data types ? import pandas as pd # Create DataFrame with multiple data types dataFrame = pd.DataFrame( ...

Read More

Python - Character repetition string combinations

AmitDiwan
AmitDiwan
Updated on 26-Mar-2026 205 Views

When generating string combinations with character repetition, we need to create all possible arrangements where each position can contain any character from the original string. This is essentially generating permutations with repetition using recursive backtracking. Example Below is a demonstration of generating all permutations with repetition − def to_string(my_list): return ''.join(my_list) def lex_recurrence(my_string, my_data, last_val, index_val): length = len(my_string) for i in range(length): my_data[index_val] = my_string[i] ...

Read More

Python - Group contiguous strings in List

AmitDiwan
AmitDiwan
Updated on 26-Mar-2026 278 Views

When working with mixed lists containing both strings and numbers, you might need to group contiguous string elements together while keeping non-string elements separate. Python's itertools.groupby() function combined with a custom key function provides an elegant solution. Understanding the Problem Given a list with mixed data types, we want to group consecutive string elements into sublists while leaving non-string elements as individual items ? Solution Using groupby() We'll create a helper function to identify strings and use groupby() to group contiguous elements ? from itertools import groupby def string_check(elem): ...

Read More

Python - Add a zero column to Pandas DataFrame

AmitDiwan
AmitDiwan
Updated on 26-Mar-2026 2K+ Views

To add a zero column to a Pandas DataFrame, you can use square bracket notation to create a new column and assign 0 to all rows. This is useful for initializing placeholder columns or creating default values. Creating the DataFrame First, let's create a sample DataFrame with student data ? import pandas as pd # Create DataFrame dataFrame = pd.DataFrame({ "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'], "Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'], "Roll Number": [5, 10, 3, 8, 2, ...

Read More

Python - Element frequencies in percent range

AmitDiwan
AmitDiwan
Updated on 26-Mar-2026 373 Views

When finding elements whose frequencies fall within a specific percentage range, we can use Python's Counter class along with percentage calculations to filter elements based on their occurrence rates. Example Below is a demonstration of finding elements with frequencies between 13% and 60% − from collections import Counter my_list = [56, 34, 78, 90, 11, 23, 6, 56, 79, 90] print("The list is :") print(my_list) start, end = 13, 60 my_freq = dict(Counter(my_list)) print("Element frequencies:", my_freq) my_result = [] for element in set(my_list): percent = (my_freq[element] / len(my_list)) * 100 print(f"Element {element}: {percent}%") if percent >= start and percent

Read More

Python Program to Get K initial powers of N

AmitDiwan
AmitDiwan
Updated on 26-Mar-2026 362 Views

When it is required to get the specific number of powers of a number, the ** operator is used along with list comprehension to generate the first K powers of N. Syntax The basic syntax for calculating powers in Python ? # Using ** operator result = base ** exponent # Using list comprehension for multiple powers powers = [base ** i for i in range(k)] Example Below is a demonstration of getting K initial powers of N ? n = 4 k = 5 print("The value n is:", ...

Read More
Showing 1–10 of 61,303 articles
« Prev 1 2 3 4 5 6131 Next »
Advertisements