Assign Each List Element Value Equal to Its Magnitude Order in Python

AmitDiwan
Updated on 15-Sep-2021 12:34:21

168 Views

When it is required to assign each list element value equal to its magnitude order, the ‘set’ operation, the ‘zip’ method and a list comprehension are used.ExampleBelow is a demonstration of the samemy_list = [91, 42, 27, 39, 24, 45, 53] print("The list is : ") print(my_list) my_ordered_dict = dict(zip(list(set(my_list)), range(len(set(my_list))))) my_result = [my_ordered_dict[elem] for elem in my_list] print("The result is: ") print(my_result)OutputThe list is : [91, 42, 27, 39, 24, 45, 53] The result is: [0, 2, 6, 1, 5, 3, 4]ExplanationA list is defined and is displayed on the console.The unique elements of the ... Read More

Strip Whitespace from a Pandas DataFrame in Python

AmitDiwan
Updated on 15-Sep-2021 12:28:27

931 Views

To strip whitespace, whether its leading or trailing, use the strip() method. At first, let us import thr required Pandas library with an alias −import pandas as pdLet’s create a DataFrame with 3 columns. The first column is having leading and trailing whitespaces −dataFrame = pd.DataFrame({    'Product Category': [' Computer', ' Mobile Phone', 'Electronics ', 'Appliances', ' Furniture', 'Stationery'], 'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Refrigerators', 'Chairs', 'Diaries'], 'Quantity': [10, 50, 10, 20, 25, 50]}) Removing whitespace from a single column “Product Category” −dataFrame['Product Category'].str.strip()ExampleFollowing is the complete code − import pandas as pd # create a dataframe ... Read More

Filter Supersequence Strings in Python

AmitDiwan
Updated on 15-Sep-2021 12:27:07

179 Views

When it is required to filter supersequence strings, a simple list comprehension is used.ExampleBelow is a demonstration of the samemy_list = ["Python", "/", "is", "alwaysgreat", "to", "learn"] print("The list is :") print(my_list) substring = "ys" my_result = [sub for sub in my_list if all(elem in sub for elem in substring)] print("The resultant string is :") print(my_result)OutputThe list is : ['Python', '/', 'is', 'alwaysgreat', 'to', 'learn'] The resultant string is : ['alwaysgreat']ExplanationA list is defined and is displayed on the console.A substring is defined.The list comprehension is used to iterate through the elements using the ‘all’ clause.This ... Read More

Maximum Difference Across Lists in Python

AmitDiwan
Updated on 15-Sep-2021 12:25:07

470 Views

When it is required to find the maximum difference across the lists, the ‘abs’ and the ‘max’ methods are used.ExampleBelow is a demonstration of the samemy_list_1 = [7, 9, 1, 2, 7] my_list_2 = [6, 3, 1, 2, 1] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) my_result = max(abs(my_list_2[index] - my_list_1[index]) for index in range(0, len(my_list_1) - 1)) print("The maximum difference among the lists is :") print(my_result)OutputThe first list is : [7, 9, 1, 2, 7] The second list is : [6, 3, 1, 2, 1] The maximum difference ... Read More

Remove Positional Rows in Python

AmitDiwan
Updated on 15-Sep-2021 12:22:58

143 Views

When it is required to remove positional rows, a simple iteration and the ‘pop’ method is used.ExampleBelow is a demonstration of the samemy_list = [[31, 42, 2], [1, 73, 29], [51, 3, 11], [0, 3, 51], [17, 3, 21], [1, 71, 10], [0, 81, 92]] print("The list is :") print(my_list) my_index_list = [1, 2, 5] for index in my_index_list[::-1]: my_list.pop(index) print("The output is :") print(my_list)OutputThe list is : [[31, 42, 2], [1, 73, 29], [51, 3, 11], [0, 3, 51], [17, 3, 21], [1, 71, 10], [0, 81, 92]] The output is : [[31, ... Read More

Compute Power by Index Element in List using Python

AmitDiwan
Updated on 15-Sep-2021 12:20:03

301 Views

When it is required to compute the power by index element in a list, the simple iteration along with the ‘**’ operator is used.ExampleBelow is a demonstration of the samemy_list = [62, 18, 12, 63, 44, 75] print("The list is :") print(my_list) my_result = [] for my_index, elem in enumerate(my_list): my_result.append(elem ** my_index) print("The result is :") print(my_result)OutputThe list is : [62, 18, 12, 63, 44, 75] The result is : [1, 18, 144, 250047, 3748096, 2373046875]ExplanationA list is defined and is displayed on the console.An empty list is defined.The list is iterated ... Read More

Groupby Values Count on Pandas DataFrame

AmitDiwan
Updated on 15-Sep-2021 12:19:04

540 Views

To Groupby value counts, use the groupby(), size() and unstack() methods of the Pandas DataFrame. At first, create a DataFrame with 3 columns −dataFrame = pd.DataFrame({    'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'], 'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'], 'Quantity': [10, 50, 10, 20, 25, 50]}) Now, groupby values count with groupby() method. For count, use the size() and unstack(). The unstack() gives a new level of column labels −dataFrame = dataFrame.groupby(['Product Category', 'Product Name', 'Quantity']).size().unstack(fill_value=0)ExampleFollowing is the complete code −import pandas as pd # create a dataframe with 3 columns ... Read More

Most Common Combination in Matrix with Python

AmitDiwan
Updated on 15-Sep-2021 12:18:39

271 Views

When it is required to find the most common combination in a matrix, a simple iteration, along with the ‘sort’ method and ‘Counter’ method is used.ExampleBelow is a demonstration of the samefrom collections import Counter from itertools import combinations my_list = [[31, 25, 77, 82], [96, 15, 23, 32]] print("The list is :") print(my_list) my_result = Counter() for elem in my_list:    if len(elem) < 2:       continue    elem.sort()    for size in range(2, len(elem) + 1):       for comb in combinations(elem, size):          my_result[comb] += ... Read More

Filter Dictionaries by Values in Kth Key in Python

AmitDiwan
Updated on 15-Sep-2021 12:18:04

261 Views

When it is required to filter dictionaries by values in ‘K’th key in a list, a simple iteration by specifying the condition is used.ExampleBelow is a demonstration of the samemy_list = [{"Python": 2, "is": 4, "cool": 11}, {"Python": 5, "is": 1, "cool": 1}, {"Python": 7, "is": 3, "cool": 7}, {"Python": 9, "is": 9, "cool": 8}, {"Python": 4, "is": 10, "cool": 6}] print("The list is :") print(my_list) search_list = [1, 9, 8, 4, 5] key = "is" my_result = [] for sub in my_list: ... Read More

Get All Pairwise Combinations from a List in Python

AmitDiwan
Updated on 15-Sep-2021 12:11:10

616 Views

When it is required to get all pairwise combinations from a list, an iteration along with the ‘append’ method is used.ExampleBelow is a demonstration of the samemy_list = [15, "John", 2, "Will", 53, 'Rob'] print("The list is :") print(my_list) my_result = [] for i in range(0, len(my_list)): for j in range(0, len(my_list)): if (i!=j): my_result.append((my_list[i], my_list[j])) print("The result is :") print(my_result)OutputThe list is : [15, 'John', 2, 'Will', 53, 'Rob'] The result is : [(15, 'John'), (15, ... Read More

Advertisements