Found 33676 Articles for Programming

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

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

498 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

414 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

560 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

Advertisements