Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Programming Articles
Page 340 of 2547
Python - Summing all the rows of a Pandas Dataframe
To sum all the rows of a DataFrame, use the sum() function with axis=1. Setting the axis parameter to 1 adds values across columns for each row, while axis=0 (default) would sum down columns. Creating a Sample DataFrame Let's start by creating a DataFrame with stock data ? import pandas as pd dataFrame = pd.DataFrame({ "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900] }) print("DataFrame...") print(dataFrame) DataFrame... Opening_Stock Closing_Stock 0 ...
Read MorePython Pandas - How to append rows to a DataFrame
To append rows to a DataFrame, use the concat() method (recommended) or the deprecated append() method. Here, we will create two DataFrames and append one after the other. Using concat() Method (Recommended) The concat() method is the modern approach for appending DataFrames ? import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame({ "Car": ['BMW', 'Lexus', 'Audi', 'Jaguar'] }) print("DataFrame1 ...", dataFrame1) print("DataFrame1 length =", len(dataFrame1)) # Create DataFrame2 dataFrame2 = pd.DataFrame({ "Car": ['Mercedes', 'Tesla', 'Bentley', 'Mustang'] }) print("DataFrame2 ...", dataFrame2) print("DataFrame2 length =", ...
Read MorePython Pandas - Create a subset by choosing specific values from columns based on indexes
To create a subset by choosing specific values from columns based on indexes, use the iloc() method. The iloc() method allows you to select data by integer position, making it perfect for choosing specific rows and columns from a DataFrame. Creating a DataFrame Let us first create a sample DataFrame with product records ? import 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) ...
Read MorePython Pandas - Subset DataFrame by Column Name
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'] Syntax # Single column - returns a Series dataFrame['column_name'] # Multiple columns - returns a DataFrame dataFrame[['col1', 'col2']] Example - Single Column Subset Let us create a DataFrame and extract a single column ? import pandas as pd # Create a Pandas DataFrame with Product records dataFrame = pd.DataFrame({ "Product": ["SmartTV", "ChromeCast", "Speaker", ...
Read MorePython – Assign Alphabet to each element
When working with integer lists, you may need to assign alphabet letters to each element based on their sorted order. Python's string.ascii_lowercase module provides lowercase letters, and we can map them to unique values using list comprehension. Syntax import string string.ascii_lowercase[index] # Returns letter at given index Example Below is a demonstration that assigns alphabets to unique elements based on their sorted order − 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() ...
Read MorePython – Dictionaries with Unique Value Lists
When working with a list of dictionaries, you may need to extract all unique values from across all dictionaries. Python provides an elegant solution using set operations and list comprehensions to eliminate duplicates efficiently. Example Below is a demonstration of extracting unique values from dictionary lists ? 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) ...
Read MorePython – Get Matrix Mean
When working with matrices in Python, calculating the mean (average) of all elements is a common operation. The NumPy package provides the mean() method to efficiently compute the mean of matrix elements. Basic Matrix Mean Here's how to calculate the mean of all elements in a matrix ? 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 mean is:") print(my_result) The matrix is: [[24 41] [35 25]] The mean is: 31.25 Mean Along Specific Axis You can calculate ...
Read MorePython – Extract Key's Value, if Key Present in List and Dictionary
Sometimes we need to extract a value from a dictionary only if the key exists in both a list and the dictionary. Python provides the all() function combined with the in operator to check multiple conditions efficiently. Basic Example Here's how to extract a key's value when the key is present in both a list and dictionary ? my_list = ["Python", "is", "fun", "to", "learn", "and", "teach", "cool", "object", "oriented"] my_dictionary = {"Python": 2, "fun": 4, "learn": 6} K = "Python" print("The key is:", K) print("The list is:", my_list) print("The dictionary is:", my_dictionary) ...
Read MorePython – Check if Splits are equal
When you need to check if all parts of a split string are equal, you can use the set() function along with split(). This approach converts the split result to a set to get unique elements, then checks if only one unique element exists. Example Below is a demonstration of checking if splits are equal ? 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(set(my_string.split(my_split_char))) == 1 print("The resultant check is :") if my_result: ...
Read MorePython – Grouped Consecutive Range Indices of Elements
Sometimes we need to group consecutive occurrences of elements in a list and track their index ranges. Python provides an efficient approach using defaultdict and groupby from the itertools module to identify consecutive elements and map their start and end indices. Understanding Grouped Consecutive Range Indices When elements appear consecutively in a list, we can group them and track their index ranges. For example, in the list [1, 1, 2, 3, 3, 3], element 1 appears at indices 0-1, element 2 at index 2, and element 3 at indices 3-5. Example with Consecutive Elements Let's create ...
Read More