Found 10476 Articles for Python

Python Pandas - How to append rows to a DataFrame

AmitDiwan
Updated on 14-Sep-2021 13:38:38

925 Views

To append rows to a DataFrame, use the append() method. Here, we will create two DataFrames and append one after the another.At first, import the pandas library with an alias −import pandas as pdNow, create the 1st DataFramedataFrame1 = pd.DataFrame(    { "Car": ['BMW', 'Lexus', 'Audi', 'Jaguar'] } )Create the 2nd DataFramedataFrame2 = pd.DataFrame( { "Car": ['Mercedes', 'Tesla', 'Bentley', 'Mustang'] } )Next, append rows to the enddataFrame1 = dataFrame1.append(dataFrame2)ExampleFollowing is the codeimport pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Jaguar'] } ) print"DataFrame1 ...", dataFrame1 # Find ... Read More

Python Pandas - Create a subset by choosing specific values from columns based on indexes

AmitDiwan
Updated on 14-Sep-2021 07:49:39

406 Views

To create a subset by choosing specific values from columns based on indexes, use the iloc() method. Let us first import the pandas libraryimport pandas as pdCreate a Pandas DataFrame with Product records. We have 3 columns in itdataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})Creating a subset with 2 columns and 1st 2 rows using iloc(print"Displaying a subset using iloc() = ", dataFrame.iloc[0:2, 0:2] 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]}) ... Read More

Python Pandas - Subset DataFrame by Column Name

AmitDiwan
Updated on 14-Sep-2021 13:30:27

497 Views

To create a subset of DataFrame by column name, use the square brackets. Use the DataFrame with square brackets (indexing operator) and the specific column name like this −dataFrame[‘column_name’]At first, import the required library with alias −import pandas as pdCreate 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]})Let us fetch a subset i.e. we are fetching only Product column recordsdataFrame['Product']ExampleFollowing is the codeimport pandas as pd dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]}) ... Read More

Python – Assign Alphabet to each element

AmitDiwan
Updated on 13-Sep-2021 11:52:58

412 Views

When it is required to assign an alphabet to every element of an integer list, the ‘ascii_lowercase’ method, and the list comprehension are used.ExampleBelow is a demonstration of the same −import string my_list = [11, 51, 32, 45, 21, 66, 12, 58, 90, 0] print("The list is : " ) print(my_list) print("The list after sorting is : " ) my_list.sort() print(my_list) temp_val = {} my_counter = 0 for element in my_list: if element in temp_val: continue temp_val[element] = string.ascii_lowercase[my_counter] my_counter ... Read More

Python – Dictionaries with Unique Value Lists

AmitDiwan
Updated on 13-Sep-2021 11:51:39

167 Views

When it is required to get the dictionaries with unique value lists, the ‘set’ operator and the list methods are used, along with a simple iteration.ExampleBelow is a demonstration of the same −my_dictionary = [{'Python' : 11, 'is' : 22}, {'fun' : 11, 'to' : 33}, {'learn' : 22}, {'object':9}, {'oriented':11}] print("The dictionary is : " ) print(my_dictionary) my_result = list(set(value for element in my_dictionary for value in element.values())) print("The resultant list is : ") print(my_result) print("The resultant list after sorting is : ") my_result.sort() print(my_result)OutputThe dictionary is : [{'Python': 11, 'is': 22}, {'fun': 11, 'to': ... Read More

Python – Get Matrix Mean

AmitDiwan
Updated on 13-Sep-2021 11:50:12

242 Views

When it is required to get the mean of the matrix elements, the ‘mean’ method from the ‘Numpy’ package is used after it has been imported into the environment.ExampleBelow is a demonstration of the same −import numpy as np my_matrix = np.matrix('[24, 41; 35, 25]') print("The matrix is : " ) print(my_matrix) my_result = my_matrix.mean() print("The result is : ") print(my_result)OutputThe matrix is : [[24 41] [35 25]] The result is : 31.25ExplanationThe required packages are imported into the environment.A matrix is created using the Numpy package.It is displayed on the console.The mean of the matrix is ... Read More

Python – Extract Key’s Value, if Key Present in List and Dictionary

AmitDiwan
Updated on 13-Sep-2021 11:49:16

558 Views

When it is required to extract the value of key if the key is present in the list as well as the dictionary, a simple iteration and the ‘all’ operator are used.ExampleBelow is a demonstration of the same −my_list = ["Python", "is", "fun", "to", "learn", "and", "teach", 'cool', 'object', 'oriented'] my_dictionary = {"Python" : 2, "fun" : 4, "learn" : 6} K = "Python" print("The value of K is ") print(K) print("The list is : " ) print(my_list) print("The dictionary is : " ) print(my_dictionary) my_result = None if all(K in sub for sub in ... Read More

Python – Sort Dictionary List by Key’s ith Index value

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

455 Views

When it is required to sort the list of dictionary based on the key’s ‘i’th index value, the ‘sorted’ method and the lambda methods are used.ExampleBelow is a demonstration of the same −my_list = [{"Python" : "Best", "to" : "Code"}, {"Python" : "Good", "to" : "Learn"}, {"Python" : "object", "to" : "cool"}, {"Python" : "oriented", "to" : "language"}] print("The list is : " ) print(my_list) K = "Python" print("The value of K is ") print(K) i = 2 print("The value of i is :") print(i) my_result = ... Read More

Python – Check if Splits are equal

AmitDiwan
Updated on 13-Sep-2021 11:45:31

272 Views

When it is required to check if the splits in a string are equal, the ‘len’ method, ‘list’ method and the ‘set’ operator are used along with an ‘if’ condition.ExampleBelow is a demonstration of the same −my_string = '96%96%96%96%96%96' print("The string is : " ) print(my_string) my_split_char = "%" print("The character on which the string should be split is :") print(my_split_char) my_result = len(list(set(my_string.split(my_split_char)))) == 1 print("The resultant list is : ") if(my_result == True): print("All the splits are equal") else: print("All the splits are not equal")OutputThe string is ... Read More

Python – Grouped Consecutive Range Indices of Elements

AmitDiwan
Updated on 13-Sep-2021 11:43:27

218 Views

When it is required to get the grouped consecutive range of indices of elements in a list, a defaultdict is created. A simple iteration, along with ‘groupby’ method, ‘len’ method, ‘list’ method and the ‘append’ methods are used.ExampleBelow is a demonstration of the same −from itertools import groupby from collections import defaultdict my_list = [63, 12, 84, 91, 52, 39, 25, 27, 20, 11, 0, 9] print("The list is : " ) print(my_list) my_index = 0 my_result = defaultdict(list) for key, sub in groupby(my_list): element = len(list(sub)) my_result[key].append((my_index, my_index + ... Read More

Advertisements