Found 26504 Articles for Server Side Programming

How to do groupby on a multiindex in Pandas?

AmitDiwan
Updated on 09-Sep-2021 06:23:53

352 Views

Multiindex Data Frame is a data frame with more than one index. Let’s say the following is our csv stored on the Desktop −At first, import the pandas library and read the above CSV file −import pandas as pd df = pd.read_csv("C:/Users/amit_/Desktop/sales.csv") print(df)We will form the ‘Car‘ and ‘Place‘ columns of the Dataframe as the index −df = df.set_index(['Car', 'Place'])The DataFrame is now a multi-indexed DataFrame having the ‘Car‘ and ‘Place‘ columns as an index.Now, let us use groupby on the multiindex dataframe:res = df.groupby(level=['Car'])['UnitsSold'].mean() print(res)ExampleFollowing is the code −import pandas as pd df = pd.read_csv("C:/Users/amit_/Desktop/sales.csv") print(df) ... Read More

Python program to find the Decreasing point in a List

AmitDiwan
Updated on 08-Sep-2021 10:50:40

226 Views

When it is required to find the decreasing point in a list, a simple iteration and the ‘break’ statement are used.ExampleBelow is a demonstration of the same −my_list = [21, 62, 53, 94, 55, 66, 18, 1, 0] print("The list is :") print(my_list) my_result = -1 for index in range(0, len(my_list) - 1):    if my_list[index + 1] < my_list[index]:       my_result = index       break print("The result is :") print(my_result)OutputThe list is : [21, 62, 53, 94, 55, 66, 18, 1, 0] The result is : 1ExplanationA list of integers is ... Read More

Python - Unique keys count for Value in Tuple List

AmitDiwan
Updated on 08-Sep-2021 10:49:19

317 Views

When it is required to get the count of the unique values in a list of tuple, ‘defaultdict’, ‘set’ operator and the ‘append’ method are used.ExampleBelow is a demonstration of the same −from collections import defaultdict my_list = [(12, 32), (12, 21), (21, 32), (89, 21), (71, 21), (89, 11), (99, 10), (8, 23), (10, 23)] print("The list is :") print(my_list) my_result = defaultdict(list) for element in my_list:    my_result[element[1]].append(element[0]) my_result = dict(my_result) result_dictionary = dict() for key in my_result:    result_dictionary[key] = len(list(set(my_result[key]))) print("The resultant list is :") print(result_dictionary)OutputThe list is ... Read More

Python – Sort by Rear Character in Strings List

AmitDiwan
Updated on 08-Sep-2021 10:47:33

171 Views

When it is required to sort the list by rear character, a method is defined that uses negative indexing to return the result.ExampleBelow is a demonstration of the same −def get_rear_position(element):    return element[-1] my_list = ['python', 'is', 'fun', 'to', 'learn'] print("The list is : ") print(my_list) my_list.sort(key = get_rear_position) print("The result is : ") print(my_list)OutputThe list is : ['python', 'is', 'fun', 'to', 'learn'] The result is : ['python', 'fun', 'learn', 'to', 'is']ExplanationA method is defined that takes element of the list as a parameter and returns the last element as output using negative indexing.A list ... Read More

Python – Sort Matrix by None frequency

AmitDiwan
Updated on 08-Sep-2021 10:46:16

151 Views

When it is required to sort a matrix by ‘None’ frequency, a method is defined that takes a parameter and uses list comprehension, ‘not’ operator and ‘len’ method to determine the result.ExampleBelow is a demonstration of the same −def get_None_freq(row):    return len([element for element in row if not element]) my_list = [[None, 24], [None, 33, 3, None], [42, 24, 55], [13, None, 24]] print("The list is : ") print(my_list) my_list.sort(key = get_None_freq) print("The result is : ") print(my_list)OutputThe list is : [[None, 24], [None, 33, 3, None], [42, 24, 55], [13, None, 24]] The result ... Read More

Python – Extract range of Consecutive similar elements ranges from string list

AmitDiwan
Updated on 08-Sep-2021 10:43:28

278 Views

When it is required to extract range of consecutive similar elements ranges from list, a simple iteration and the ‘append’ method is used.ExampleBelow is a demonstration of the same −my_list = [12, 23, 23, 23, 48, 48, 36, 17, 17] print("The list is : ") print(my_list) my_result = [] index = 0 while index < (len(my_list)):    start_position = index    val = my_list[index]    while (index < len(my_list) and my_list[index] == val):       index += 1    end_position = index - 1    my_result.append((val, start_position, end_position)) print("The my_result is :") print(my_result)OutputThe ... Read More

Python – Filter Tuples with Strings of specific characters

AmitDiwan
Updated on 08-Sep-2021 10:41:53

252 Views

When it is required to filter tuples with strings that have specific characters, a list comprehension and the ‘all’ operator is used.ExampleBelow is a demonstration of the same −my_list = [('pyt', 'best'), ('pyt', 'good'), ('fest', 'pyt')] print("The list is :") print(my_list) char_string = 'pyestb' my_result = [index for index in my_list if all(all(sub in char_string for sub in element) for element in index)] print("The result is : ") print(my_result)OutputThe list is : [('pyt', 'best'), ('pyt', 'good'), ('fest', 'pyt')] The result is : [('pyt', 'best')]ExplanationA list of tuple is defined and displayed on the console.A string is ... Read More

Python – Filter rows with Elements as Multiple of K

AmitDiwan
Updated on 08-Sep-2021 10:40:16

167 Views

When it is required to filter rows with elements which are multiples of K, a list comprehension and modulus operator are used.ExampleBelow is a demonstration of the same −my_list = [[15, 10, 25], [14, 28, 23], [120, 55], [55, 30, 203]] print("The list is :") print(my_list) K = 5 print("The value of K is ") print(K) my_result = [index for index in my_list if all(element % K == 0 for element in index)] print("The result is :") print(my_result)OutputThe list is : [[15, 10, 25], [14, 28, 23], [120, 55], [55, 30, 203]] The value of K ... Read More

Python – Character indices Mapping in String List

AmitDiwan
Updated on 08-Sep-2021 10:38:59

579 Views

When it is required to find character indices that map to a string list, a simple iteration, list comprehension and ‘add’ method is used.ExampleBelow is a demonstration of the same −from collections import defaultdict my_list = ['p y t h o n', 'i s', 'f u n', 't o', 'l e a r n'] print("The list is :") print(my_list) my_result = defaultdict(set) for index, element in enumerate(my_list):    for sub in element.split():       my_result[sub].add(index + 1) my_result = {key: list(val) for key, val in my_result.items()} print("The result is :") print(my_result)OutputThe list is ... Read More

Python – Extract dictionaries with values sum greater than K

AmitDiwan
Updated on 08-Sep-2021 10:37:29

496 Views

When it is required to extract dictionaries with values sum greater than K, a simple iteration and ‘if’ condition is used.ExampleBelow is a demonstration of the same −my_list = [{"Python" : 14, "is" : 18, "fun" : 19}, {"Python" : 12, "is": 4, "fun" : 16}, {"Python" : 13, "is": 17, "fun" : 11}, {"Python" : 13, "is": 16, "fun" : 13}] print("The list :") print(my_list) K =35 print("The value for K :") print(K) my_result = [] for index in my_list:    sum = 0    for key in index:       sum += index[key]   ... Read More

Advertisements