Found 10476 Articles for Python

Python – Filter consecutive elements Tuples

AmitDiwan
Updated on 13-Sep-2021 11:06:53

281 Views

When it is required to filter consecutive elements from a list of tuple, a method is defined that takes a list of tuple as a parameter and checks the index of every tuple, and returns a Boolean value depending on the index.ExampleBelow is a demonstration of the same −print("Method definition begins...") def check_consec_tuple_elem(my_tuple):    for idx in range(len(my_tuple) - 1):       if my_tuple[idx + 1] != my_tuple[idx] + 1:          return False    return True print("Method definition ends...") my_tuple = [(23, 24, 25, 26), (65, 66, 78, 29), (11, 28, 39), (60, 61, 62, 63)] ... Read More

Python – Remove Rows for similar Kth column element

AmitDiwan
Updated on 13-Sep-2021 11:04:30

120 Views

When it is required to remove rows for a similar ‘K’th column element, a simple iteration, and the ‘append’ method are used.ExampleBelow is a demonstration of the same −my_list = [[45, 95, 26], [70, 35, 74], [87, 65, 23], [70, 35, 74], [67, 85, 12], [45, 65, 0]] print("The list is : " ) print(my_list) K = 1 print("The value of K is ") print(K) my_result = [] my_mem = [] for index in my_list:    if not index[K] in my_mem:       my_result.append(index)       my_mem.append(index[K]) print("The resultant list is : ") ... Read More

Python – Count frequency of sublist in given list

AmitDiwan
Updated on 13-Sep-2021 11:01:44

460 Views

When it is required to count the frequency of a sub-list in a given list, a list comprehension and the ‘len’ method along with the ‘if’ condition are used.ExampleBelow is a demonstration of the same −my_list = [23, 33, 45, 67, 54 , 43, 33, 45, 67, 83, 33, 45, 67, 90, 0] print("The list is : " ) print(my_list) sub_list = [33, 45, 67, 90] print("The sub-list is : " ) print(sub_list) my_result = len([sub_list for index in range(len(my_list)) if my_list[index : index + len(sub_list)] == sub_list]) print("The resultant list is : ") print(my_result)OutputThe list ... Read More

Python – Segregate elements by delimiter

AmitDiwan
Updated on 13-Sep-2021 10:59:06

191 Views

When it is required to segregate elements based on a delimiter, ExampleBelow is a demonstration of the same −my_list = ["89@21", "58@51", "19@61", "11@10", "32@65", "34@45", "87@90", "32@21", '1@345'] print("The list is : " ) print(my_list) print("The list after sorting is :") my_list.sort() print(my_list) my_delimiter = "@" print("The delimiter is :") print(my_delimiter) result_before_delim, result_after_delim = [ele.split(my_delimiter)[0] for ele in my_list], [ele.split(my_delimiter)[1] for ele in my_list] print("The result containing elements before delimiter is : ") print(result_before_delim) print("The result containing elements after delimiter is : ") print(result_after_delim)OutputThe list is : ['89@21', '58@51', '19@61', '11@10', '32@65', '34@45', '87@90', ... Read More

Python – Extract elements in between multiple specific range of index

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

720 Views

When it is required to extract elements that are in between multiple specific range of index, the ‘extend’ method, a simple iteration and indexing are used.ExampleBelow is a demonstration of the same −my_list = [13, 21, 81, 10, 13, 17, 22, 18, 11, 90, 0] print("The list is : ") print(my_list) print("The list after sorting is : " ) my_list.sort() print(my_list) range_list = [(2, 4), (7, 8), (1, 2), (2, 7)] my_result = [] for element in range_list: my_result.extend(my_list[element[0] : element[1] + 1]) print("The resultant list is : ") print(my_result) print("The result ... Read More

Python – Sort List items on basis of their Digits

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

368 Views

When it is required to sort the elements of a list based on the digits, the ‘max’, ‘max’ method are used. We will also use the ‘sorted’ method, the ‘lambda’ function and ‘ljust’.ExampleBelow is a demonstration of the same −my_list = [4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1] print("The list is : " ) print(my_list) print("The list after sorting is : " ) my_list.sort() print(my_list) my_temp_val = map(str, my_list) my_max_length = max(map(len, my_temp_val)) my_result = sorted(my_list, key = lambda index : (str(index).ljust(my_max_length, 'a'))) print("The resultant list is ... Read More

Python – Random insertion of elements K times

AmitDiwan
Updated on 13-Sep-2021 10:43:09

301 Views

When it is required to randomly insert elements K times, the ‘random’ package and methods from the random package along with a simple iteration is used.ExampleBelow is a demonstration of the same −import random my_list = [34, 12, 21, 56, 8, 9, 0, 3, 41, 11, 90] print("The list is : " ) print(my_list) print("The list after sorting is : " ) my_list.sort() print(my_list) to_add_list = ["Python", "Object", "oriented", "language", 'cool'] K = 3 print("The value of K is ") print(K) for element in range(K): index = random.randint(0, len(my_list)) ... Read More

Python program to find all the Combinations in a list with the given condition

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

575 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

Python Pandas - Query the columns of a DataFrame

AmitDiwan
Updated on 14-Sep-2021 15:22:09

416 Views

To query the columns of a Pandas DataFrame, use the query(). We are querying to filter records. At first, let us create a Pandas DataFramedataFrame = pd.DataFrame({"Product": ["SmartTV", "PenDrive", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})Using query() to query columns with conditions −print(dataFrame.query('Opening_Stock >=500 & Closing_Stock < 1000 & Product.str.startswith("P").values'))ExampleFollowing is the complete code −import pandas as pd dataFrame = pd.DataFrame({"Product": ["SmartTV", "PenDrive", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]}) print"DataFrame...", dataFrame # using query() to query columns print"Querying columns to filter records..." print(dataFrame.query('Opening_Stock >=500 & Closing_Stock ... Read More

Python Pandas - How to select multiple rows from a DataFrame

AmitDiwan
Updated on 14-Sep-2021 15:14:34

3K+ Views

To select multiple rows from a DataFrame, set the range using the : operator. At first, import the require pandas library with alias −import pandas as pdNow, create a new Pandas DataFrame −dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]], index=['w', 'x', 'y', 'z'], columns=['a', 'b'])Select multiple rows using the : operator −dataFrame[0:2]ExampleFollowing is the code −import pandas as pd # Create DataFrame dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]], index=['w', 'x', 'y', 'z'], columns=['a', 'b']) # DataFrame print"DataFrame...", dataFrame # select rows with loc print"Select rows by passing label..." print(dataFrame.loc['z']) ... Read More

Advertisements