Found 10476 Articles for Python

Python – Extract rows with Complex data types

AmitDiwan
Updated on 14-Sep-2021 10:34:58

139 Views

When it is required to extract rows with complex data types, the ‘isinstance’ method and list comprehension are used.ExampleBelow is a demonstration of the samemy_list = [[13, 1, 35], [23, [44, 54], 85], [66], [75, (81, 2), 29, 7]] my_result = [row for row in my_list if any(isinstance(element, list) or isinstance(element, tuple) or isinstance(element, dict) or isinstance(element, set) for element in row)] print("The list is :") print(my_list) print("The resultant list is :") print(my_result)OutputThe list is : [[13, 1, 35], [23, [44, 54], 85], [66], [75, (81, 2), 29, 7]] The resultant list is : [[23, [44, 54], ... Read More

Python Program to return the Length of the Longest Word from the List of Words

AmitDiwan
Updated on 14-Sep-2021 10:33:19

1K+ Views

When it is required to return the length of the longest word from a list of words, a method is defined that takes a list as parameter. It checks if an element is in the list and depending on this, the output is displayed.ExampleBelow is a demonstration of the samedef find_longest_length(my_list):    max_length = len(my_list[0])    temp = my_list[0]    for element in my_list:       if(len(element) > max_length):          max_length = len(element)          temp = element return max_length my_list = ["ab", "abc", "abcd", "abcde"] print("The list ... Read More

Python Program to Sort Matrix Rows by summation of consecutive difference of elements

AmitDiwan
Updated on 14-Sep-2021 10:31:43

192 Views

ExampleBelow is a demonstration of the samedef diff_summation_elem(row): return sum([abs(row[index + 1] - row[index]) for index in range(0, len(row) - 1)]) my_list = [[97, 6, 47, 3], [6, 88, 3, 26], [71, 53, 34, 65], [15, 36, 5, 62]] print("The list is : ") print(my_list) my_list.sort(key=diff_summation_elem) print("The resultant list is :" ) print(my_list)OutputThe list is : [[97, 6, 47, 3], [6, 88, 3, 26], [71, 53, 34, 65], [15, 36, 5, 62]] The resultant list is : [[71, 53, 34, 65], [15, 36, 5, 62], [97, 6, 47, 3], [6, 88, 3, 26]]ExplanationA ... Read More

Python – Append given number with every element of the list

AmitDiwan
Updated on 14-Sep-2021 10:28:01

337 Views

When it is required to append given number with every element of the list, a list comprehension is used.ExampleBelow is a demonstration of the samemy_list = [25, 36, 75, 36, 17, 7, 8, 0] print ("The list is :") print(my_list) my_key = 6 my_result = [x + my_key for x in my_list] print ("The resultant list is :") print(my_result)OutputThe list is : [25, 36, 75, 36, 17, 7, 8, 0] The resultant list is : [31, 42, 81, 42, 23, 13, 14, 6]ExplanationA list is defined and is displayed on the console.An integer value for key ... Read More

Python – Cumulative Row Frequencies in a List

AmitDiwan
Updated on 14-Sep-2021 10:26:49

303 Views

When it is required to get the cumulative row frequencies in a list, the ‘Counter’ method, and a list comprehension are used.ExampleBelow is a demonstration of the samefrom collections import Counter my_list = [[11, 2, 32, 4, 31], [52, 52, 3, 71, 71, 3], [1, 3], [19, 19, 40, 40, 40]] print("The list is :") print(my_list) my_element_list = [19, 2, 71] my_frequency = [Counter(element) for element in my_list] my_result = [sum([freq[word] for word in my_element_list if word in freq]) for freq in my_frequency] print("The resultant matrix is :") print(my_result)OutputThe list is : [[11, 2, ... Read More

Python Program To Get Minimum Element For String Construction

AmitDiwan
Updated on 14-Sep-2021 10:19:58

129 Views

When it is required to get the minimum element to construct a string, the ‘set’ operator, the ‘combinations’ method, the ‘issubset’ method and a simple iteration is required.ExampleBelow is a demonstration of the samefrom itertools import combinations my_list = ["python", "is", "fun", "to", "learn"] print("The list is :") print(my_list) my_target_str = "onis" my_result = -1 my_set_string = set(my_target_str) complete_val = False for value in range(0, len(my_list) + 1): for sub in combinations(my_list, value): temp_set = set(ele for subl in sub for ele in subl) ... Read More

Python Pandas - Create a Subset DataFrame using Indexing Operator

AmitDiwan
Updated on 14-Sep-2021 13:43:57

310 Views

The indexing operator is the square brackets for creating a subset dataframe. Let us first create a Pandas DataFrame. We have 3 columns in the DataFramedataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})Creating a subset with a single columndataFrame[['Product']]Creating a subset with multiple columnsdataFrame[['Opening_Stock', 'Closing_Stock']]ExampleFollowing is the complete codeimport pandas as pd dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]}) print"DataFrame...", dataFrame print"Displaying a subset using indexing operator:", dataFrame[['Product']] print"Displaying a subset with multiple columns:", dataFrame[['Opening_Stock', 'Closing_Stock']]OutputThis will ... Read More

Python - Filter Pandas DataFrame with numpy

AmitDiwan
Updated on 14-Sep-2021 13:41:47

5K+ Views

The numpy where() method can be used to filter Pandas DataFrame. Mention the conditions in the where() method. At first, let us import the required libraries with their respective aliasimport pandas as pd import numpy as npWe will now create a Pandas DataFrame with Product records dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})Use numpy where() to filter DataFrame with 2 ConditionsresValues1 = np.where((dataFrame['Opening_Stock']>=700) & (dataFrame['Closing_Stock']< 1000)) print"Filtered DataFrame Value = ", dataFrame.loc[resValues1] Let us use numpy where() again to filter DataFrame with 3 conditionsresValues2 = np.where((dataFrame['Opening_Stock']>=500) & (dataFrame['Closing_Stock']< 1000) ... Read More

Python - Summing all the rows of a Pandas Dataframe

AmitDiwan
Updated on 14-Sep-2021 08:24:49

17K+ Views

To sum all the rows of a DataFrame, use the sum() function and set the axis value as 1. The value axis 1 will add the row values.At first, let us create a DataFrame. We have Opening and Closing Stock columns in itdataFrame = pd.DataFrame({"Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})Finding sum of row values. Axis is set 1 to add row valuesdataFrame = dataFrame.sum(axis = 1) ExampleFollowing is the complete code import pandas as pd dataFrame = pd.DataFrame({"Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]}) print"DataFrame...", dataFrame # finding sum of ... Read More

Python Pandas - How to delete a row from a DataFrame

AmitDiwan
Updated on 23-Aug-2023 21:13:18

63K+ Views

To delete a row from a DataFrame, use the drop() method and set the index label as the parameter.At first, let us create a DataFrame. We have index label as w, x, y, and z:dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]], index=['w', 'x', 'y', 'z'], columns=['a', 'b'])Now, let us use the index label and delete a row. Here, we will delete a row with index label 'w'.dataFrame = dataFrame.drop('w') ExampleFollowing is the codeimport pandas as pd # Create DataFrame dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]], index=['w', 'x', 'y', 'z'], columns=['a', 'b']) ... Read More

Advertisements