Find All Combinations in a List with Given Condition in Python

AmitDiwan
Updated on 13-Sep-2021 10:40:48

589 Views

When it is required to find all the combinations in a list with a specific condition, a simple iteration, the ‘isinstance’ method, the ‘append’ method and indexing are used.ExampleBelow is a demonstration of the same −print("Method definition begins") def merge_the_vals(my_list_1, my_list_2, K): index_1 = 0 index_2 = 0 while(index_1 < len(my_list_1)): for i in range(K): yield my_list_1[index_1] index_1 += 1 ... Read More

Drop Multiple Levels from Multi-Level Column Index in Pandas DataFrame

AmitDiwan
Updated on 13-Sep-2021 09:15:08

6K+ Views

To drop multiple levels from a multi-level column index, use the columns.droplevel() repeatedly. We have used the Multiindex.from_tuples() is used to create indexes column-wise.At first, create indexes column-wise −items = pd.MultiIndex.from_tuples([("Col 1", "Col 1", "Col 1"), ("Col 2", "Col 2", "Col 2"), ("Col 3", "Col 3", "Col 3")])Next, create a multiindex array and form a multiindex dataframe −arr = [np.array(['car', 'car', 'car', 'bike', 'bike', 'bike', 'truck', 'truck', 'truck']), np.array(['valueA', 'valueB', 'valueC', 'valueA', 'valueB', 'valueC', 'valueA', 'valueB', 'valueC'])] # forming multiindex dataframe dataFrame = pd.DataFrame(np.random.randn(9, 3), index=arr, columns=items)Label the index −dataFrame.index.names = ['level 0', 'level 1'] Drop a level ... Read More

Convert String to Matrix Having K Characters Per Row in Python

AmitDiwan
Updated on 13-Sep-2021 08:19:15

757 Views

When it is required to convert a string into a matrix that has ‘K’ characters per row, a method is defined that takes a string and a value for ‘K’. It uses a simple iteration, the modulus operator and the ‘append’ method.ExampleBelow is a demonstration of the same −print("Method definition begins") def convert_my_string(my_string, my_k): for index in range(len(my_string)): if index % my_k == 0: sub = my_string[index:index+my_k] my_list = [] ... Read More

Convert List of Strings to List of Tuples in Python

AmitDiwan
Updated on 13-Sep-2021 08:14:05

339 Views

When it is required to convert a list of strings with a delimiter to a list of tuples, a K value is set, and list comprehension along with the ‘split’ method is used.ExampleBelow is a demonstration of the same −my_list = ["33-22", "13-44-81-39", "42-10-42", "36-56-90", "34-77-91"] print("The list is : " ) print(my_list) print("The sorted list is ") my_list.sort() print(my_list) K = "-" print("The value of K is ") print(K) my_result = [tuple(int(element) for element in sub.split(K)) for sub in my_list] print("The resultant list is : ") print(my_result)OutputThe list is : ['33-22', '13-44-81-39', '42-10-42', '36-56-90', '34-77-91'] ... Read More

Sort Grouped Pandas DataFrame by Group Size in Descending Order

AmitDiwan
Updated on 13-Sep-2021 08:03:05

4K+ Views

To group Pandas dataframe, we use groupby(). To sort grouped dataframe in descending order, use sort_values(). The size() method is used to get the dataframe size.For descending order sort, use the following in sort_values() −ascending=FalseAt first, create a pandas dataframe −dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'], "Reg_Price": [1000, 1400, 1000, 900, 1700, 900] } )Next, group according to Reg_Price column and sort in descending order −dataFrame.groupby('Reg_Price').size().sort_values(ascending=False) ExampleFollowing is the codeimport pandas as pd # dataframe with one of the columns as Reg_Price ... Read More

Sort List of Strings by Numeric Part in Python

AmitDiwan
Updated on 13-Sep-2021 07:49:18

995 Views

When it is required to sort a given list of strings based on a numeric part of the string, a method is defined that uses the regular expressions, the ‘map’ method and the ‘list’ method to display the result.ExampleBelow is a demonstration of the same −import re print("The regular expression package has been imported successfully.") def my_digit_sort(my_list): return list(map(int, re.findall(r'\d+', my_list)))[0] my_list = ["pyt23hon", "fu30n", "lea14rn", 'co00l', 'ob8uje3345t'] print("The list is : " ) print(my_list) my_list.sort(key=my_digit_sort) print("The list has been sorted based on the pre-defined method..") print("The resultant list is : ") ... Read More

Test for Desired String Lengths in Python

AmitDiwan
Updated on 13-Sep-2021 07:45:53

184 Views

When it is required to test for desired string lengths, a simple iteration, and the ‘len’ method is used.ExampleBelow is a demonstration of the same −my_list = ["python", 'is', 'fun', 'to', 'learn', 'Will', 'how'] print("The list is :") print(my_list) length_list = [6, 2, 3, 2, 5, 4, 3] my_result = True for index in range(len(my_list)):    if len(my_list[index]) != length_list[index]:       my_result = False break print("The result is :") if(my_result == True):    print("All the strings are of required lengths") else:    print("All the strings are not of required lengths")OutputThe list is : ... Read More

Sort List of Strings by Number of Unique Characters in Python

AmitDiwan
Updated on 13-Sep-2021 07:45:23

315 Views

When it is required to sort a list of strings based on the number of unique characters, a method is defined that uses a ‘set’ operator, the ‘list’ method and the ‘len’ method.ExampleBelow is a demonstration of the same −def my_sort_func(my_elem): return len(list(set(my_elem))) my_list = ['python', "Will", "Hi", "how", 'fun', 'learn', 'code'] print("The list is : ") print(my_list) my_list.sort(key = my_sort_func) print("The result is :") print(my_list)OutputThe list is : ['python', 'Will', 'Hi', 'how', 'fun', 'learn', 'code'] The result is : ['Hi', 'Will', 'how', 'fun', 'code', 'learn', 'python']ExplanationA method named ‘my_sort_func’ is defined, that takes ... Read More

Substitute Prefix in Part of List in Python

AmitDiwan
Updated on 13-Sep-2021 07:39:39

199 Views

When it is required to substitute prefix part of a list, the ‘len’ method and the ‘:’ operator is used.ExampleBelow is a demonstration of the same −my_list_1 = [15, 44, 82] my_list_2 = [29, 77, 19, 44, 26, 18] print("The first list is : " ) print(my_list_1) print("The second list is : " ) print(my_list_2) print("The first list after sorting is :") my_list_1.sort() print(my_list_1) print("The first list after sorting is :") my_list_2.sort() print(my_list_2) my_result = my_list_1 + my_list_2[len(my_list_1) : ] print("The resultant list is : ") print(my_result)OutputThe first list is : [15, 44, 82] ... Read More

Cross Mapping of Two Dictionary Value Lists in Python

AmitDiwan
Updated on 13-Sep-2021 07:35:34

657 Views

When it is required to cross-map two dictionary valued lists, the ‘setdefault’ and ‘extend’ methods are used.ExampleBelow is a demonstration of the same −my_dict_1 = {"Python" : [4, 7], "Fun" : [8, 6]} my_dict_2 = {6 : [5, 7], 8 : [3, 6], 7 : [9, 8]} print("The first dictionary is : " ) print(my_dict_1) print("The second dictionary is : " ) print(my_dict_2) sorted(my_dict_1.items(), key=lambda e: e[1][1]) print("The first dictionary after sorting is ") print(my_dict_1) sorted(my_dict_2.items(), key=lambda e: e[1][1]) print("The second dictionary after sorting is ") print(my_dict_2) my_result = {} for key, value in my_dict_1.items(): ... Read More

Advertisements