Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Articles on Trending Technologies
Technical articles with clear explanations and examples
Python – Stacking a single-level column with Pandas stack()?
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 MorePython - Create nested list containing values as the count of list items
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 MorePython - Count the frequency of matrix row length
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 MorePython - How to rename multiple column headers in a Pandas DataFrame with Dictionary?
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 MorePython - Select columns with specific datatypes
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 MorePython - Character repetition string combinations
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 MorePython - Group contiguous strings in List
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 MorePython - Add a zero column to Pandas DataFrame
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 MorePython - Element frequencies in percent range
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 MorePython Program to Get K initial powers of N
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