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
Programming Articles
Page 325 of 2547
Python – N sized substrings with K distinct characters
When working with strings, you might need to find all substrings of a specific length that contain exactly K distinct characters. This can be achieved by iterating through the string and using Python's set() method to count unique characters in each substring. Syntax The general approach involves: for i in range(len(string) - n + 1): substring = string[i:i+n] if len(set(substring)) == k: # Add to result Example Below is a demonstration that finds all 2-character substrings with ...
Read MorePython – Merge Dictionaries List with duplicate Keys
When working with lists of dictionaries, you often need to merge them while handling duplicate keys. This process involves iterating through corresponding dictionaries and adding keys that don't already exist. Basic Dictionary List Merging Here's how to merge two lists of dictionaries, keeping original values for duplicate keys ? list1 = [{"aba": 1, "best": 4}, {"python": 10, "fun": 15}, {"scala": "fun"}] list2 = [{"scala": 6}, {"python": 3, "best": 10}, {"java": 1}] print("First list:") print(list1) print("Second list:") print(list2) # Merge dictionaries at corresponding positions for i in range(len(list1)): existing_keys = list(list1[i].keys()) ...
Read MorePython Pandas - Sort DataFrame in descending order according to the element frequency
To sort a Pandas DataFrame in descending order according to element frequency, you need to group the data, count occurrences, and use sort_values() with ascending=False. Basic Syntax The key is combining groupby(), count(), and sort_values() ? df.groupby(['column']).count().sort_values(['count_column'], ascending=False) Creating Sample Data Let's create a DataFrame with car data to demonstrate frequency sorting ? import pandas as pd # Create DataFrame with duplicate car entries dataFrame = pd.DataFrame({ "Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'], "Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000], ...
Read MorePython - Move a column to the first position in Pandas DataFrame?
Use pop() to remove a column and insert() to place it at the first position in a Pandas DataFrame. This technique allows you to reorder columns efficiently without creating a new DataFrame. Creating the DataFrame First, let's create a sample DataFrame with three columns ? 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'], ...
Read MorePython – Display only non-duplicate values from a DataFrame
In this tutorial, we will learn how to display only non-duplicate values from a Pandas DataFrame. We'll use the duplicated() method combined with the logical NOT operator (~) to filter out duplicate entries. Creating a DataFrame with Duplicates First, let's create a DataFrame containing duplicate values ? import pandas as pd # Create DataFrame with duplicate student names dataFrame = pd.DataFrame({ "Student": ['Jack', 'Robin', 'Ted', 'Robin', 'Scarlett', 'Kat', 'Ted'], "Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'] }) print("Original DataFrame:") print(dataFrame) Original DataFrame: ...
Read MorePython – Reshape the data in a Pandas DataFrame
Reshaping data in Pandas involves transforming data structure to make it more suitable for analysis. One common approach is categorizing text values into numerical form using the map() function with a dictionary. Basic DataFrame Creation First, let's create a DataFrame with student names and their results ? import pandas as pd # Create DataFrame with student results dataFrame = pd.DataFrame({ "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'], "Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass'] }) print("Original DataFrame:") print(dataFrame) Original DataFrame: Student Result ...
Read MorePython - Convert Pandas DataFrame to binary data
Use the get_dummies() method to convert categorical DataFrame to binary data. This process creates binary columns for each unique category, where 1 indicates the presence of that category and 0 indicates absence. Creating a Sample DataFrame Let's start by creating a DataFrame with categorical data ? import pandas as pd # Create DataFrame with categorical data dataFrame = pd.DataFrame( { "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'], "Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass'] ...
Read MorePython – Remove Columns of Duplicate Elements
When working with lists of lists, you may need to remove columns that contain duplicate elements within each row. Python provides an elegant solution using sets to track duplicates and list comprehension to filter columns. Understanding the Problem Given a list of lists, we want to remove columns (same index positions) where any row has duplicate elements at that position within the same row. Solution Using Set-Based Duplicate Detection The approach involves creating a helper function that identifies duplicate positions and then filtering out those columns ? from itertools import chain def find_duplicate_positions(row): ...
Read MorePython - Rename column names by index in a Pandas DataFrame without using rename()
Sometimes you need to rename column names in a Pandas DataFrame by their position (index) rather than by name. Python provides a simple way to do this by directly modifying the columns.values array without using the rename() method. Using columns.values with Index You can rename columns by accessing their position in the columns.values array. This approach is useful when you know the column positions but not necessarily their current names. Example Let's create a DataFrame and rename all columns by their index positions − import pandas as pd # Create DataFrame dataFrame = ...
Read MorePython – Element wise Matrix Difference
When working with matrices represented as lists of lists in Python, you often need to compute the element-wise difference between two matrices. This operation subtracts corresponding elements from each matrix position. Using Nested Loops with zip() The most straightforward approach uses nested loops with Python's zip() function to iterate through corresponding elements ? matrix_1 = [[3, 4, 4], [4, 3, 1], [4, 8, 3]] matrix_2 = [[5, 4, 7], [9, 7, 5], [4, 8, 4]] print("First matrix:") print(matrix_1) print("Second matrix:") print(matrix_2) result = [] for row_1, row_2 in zip(matrix_1, matrix_2): ...
Read More