Programming Articles - Page 1086 of 3363

Python - How to Merge all excel files in a folder

AmitDiwan
Updated on 27-Sep-2021 12:43:43

11K+ Views

To merge all excel files in a folder, use the Glob module and the append() method.Let’s say the following are our excel files on the Desktop −Sales1.xlsxSales2.xlsxNote − You may need to install openpyxl and xlrd packages.At first, set the path where all the excel files you want to merge are located. Get the excel files and read them using glob −path = "C:\Users\amit_\Desktop\" filenames = glob.glob(path + "\*.xlsx") print('File names:', filenames)Next, create an empty dataframe for the merged output excel file that will get the data from the above two excel files −outputxlsx = pd.DataFrame()Now, the actual process ... Read More

How to count frequency of itemsets in Pandas DataFrame

AmitDiwan
Updated on 09-Sep-2021 08:47:43

345 Views

Use the Series.value_counts() method to count frequency of itemsets. At first, let us create a DataFrame −# Create DataFrame dataFrame = pd.DataFrame({'Car': ['BMW', 'Mercedes', 'Lamborghini', 'Audi', 'Mercedes', 'Porsche', 'Lamborghini', 'BMW'], 'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Bangalore', 'Hyderabad', 'Mumbai', 'Mumbai', 'Pune'], 'UnitsSold': [95, 80, 80, 75, 92, 90, 95, 50 ]})Count the frequency of column car using the value_counts() method −# counting frequency of column Car count1 = dataFrame['Car'].value_counts() print("Count in column Car") print(count1)In the same way, count the frequency of other columns. Following is the complete code to count frequency of itemsets in Pandas DataFrame ... Read More

How to add column from another DataFrame in Pandas?

AmitDiwan
Updated on 09-Sep-2021 07:08:56

6K+ Views

The insert() method is used to add a column from another DataFrame. At first, let us create our first DataFrame −dataFrame1 = pd.DataFrame({"Car": ["Audi", "Lamborghini", "BMW", "Lexus"],    "Place": ["US", "UK", "India", "Australia"],    "Units": [200, 500, 800, 1000]})Now, let us create our second DataFrame −dataFrame2 = pd.DataFrame({"Model": [2018, 2019, 2020, 2021], "CC": [3000, 2800, 3500, 3300]})Car column added from DataFrame1 to DataFrame2# Car column to be added to the second dataframe fetched_col = dataFrame1["Car"]ExampleFollowing is the code −import pandas as pd dataFrame1 = pd.DataFrame({"Car": ["Audi", "Lamborghini", "BMW", "Lexus"],    "Place": ["US", "UK", "India", "Australia"],    "Units": [200, 500, ... Read More

Python program to find Most Frequent Character in a String

AmitDiwan
Updated on 09-Sep-2021 06:14:20

4K+ Views

When it is required to find the most frequent character in a string, an empty dictionary is created, and the elements in the string are iterated over. When a character is found in the dictionary, it is increment, else it is assigned to 1. The maximum of the values in the dictionary is found, and assigned to a variable.ExampleBelow is a demonstration of the samemy_string = "Python-Interpreter" print ("The string is : ") print(my_string) max_frequency = {} for i in my_string:    if i in max_frequency:       max_frequency[i] += 1    else:       max_frequency[i] ... Read More

How to do groupby on a multiindex in Pandas?

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

384 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

238 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

341 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

193 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

168 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

302 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

Advertisements