Converting a Pandas DataFrame to LaTeX format is useful for creating professional documents and research papers. The to_latex() method generates LaTeX table code that can be directly used in LaTeX documents. Basic DataFrame to LaTeX Conversion Let's start by creating a sample DataFrame and converting it to LaTeX format ? import pandas as pd df = pd.DataFrame({ 'Id': [1, 2, 3, 4, 5], 'Age': [12, 13, 14, 15, 16] }) print("Original DataFrame:") print(df) print("LaTeX output:") print(df.to_latex(index=True, multirow=True)) Original DataFrame: Id ... Read More
This program generates a series of random four-digit PIN numbers. The user must provide an even number for the series length, and the program will keep asking until a valid even number is entered. Problem Requirements We need to: Get series length from user input Validate that the length is even Generate random four-digit PIN numbers Display the series using pandas Step-by-Step Solution Step 1: Input Validation First, we create a loop to get valid even input from the user ? while(True): size = int(input("enter the ... Read More
When working with pandas DataFrames, you might need to filter cities that share the same starting letter with other cities. This tutorial shows how to remove cities with unique prefixes (first letters) and keep only those cities whose first letter appears in multiple city names. Understanding the Problem Given a DataFrame with city names, we want to filter out cities that have unique starting letters. For example, if only one city starts with 'C', we exclude it. If multiple cities start with 'K', we keep all of them. Step-by-Step Solution Step 1: Create the DataFrame ... Read More
In this tutorial, we'll learn how to convert a Celsius column to Fahrenheit in a Pandas DataFrame. The conversion formula is: Fahrenheit = (9/5) × Celsius + 32. We'll explore two common approaches using assign() and apply() methods. Using assign() Method The assign() method creates a new column while keeping the original DataFrame unchanged. It uses a lambda function to apply the conversion formula ? import pandas as pd # Create DataFrame with temperature data df = pd.DataFrame({ 'Id': [1, 2, 3, 4, 5], 'Celsius': [37.5, ... Read More
A magic number is a number whose digits sum up to 1 or 10. In this tutorial, we'll create a Pandas series containing all magic numbers from 1 to 100. We'll explore two different approaches to solve this problem. What are Magic Numbers? Magic numbers are numbers where the sum of digits equals 1 or 10. For example: 1 → sum = 1 (magic number) 10 → sum = 1 + 0 = 1 (magic number) 19 → sum = 1 + 9 = 10 (magic number) 28 → sum = 2 + 8 = 10 ... Read More
A palindrome is a word that reads the same forwards and backwards. In this tutorial, we'll learn how to filter palindrome names from a Pandas DataFrame using different approaches. Using List Comprehension This approach uses list comprehension to identify palindromes by comparing each name with its reverse using slicing [::-1] ? import pandas as pd data = {'Id': [1, 2, 3, 4, 5], 'Name': ['bob', 'peter', 'hannah', 'james', 'david']} df = pd.DataFrame(data) print("DataFrame is:") print(df) # Find palindrome names using list comprehension palindromes = [name for name in df['Name'] if name == name[::-1]] result ... Read More
In Pandas, you can localize a DataFrame's datetime index to an Asian timezone using pd.date_range() with the tz parameter. This creates timezone-aware datetime indices for time series data. Creating a Timezone-Localized DataFrame To localize a DataFrame to an Asian timezone, follow these steps − Create a DataFrame with your data Generate a timezone-aware datetime index using pd.date_range() with tz='Asia/Calcutta' Assign the localized time index to the DataFrame's index Syntax time_index = pd.date_range(start, periods=n, freq='W', tz='Asia/Calcutta') df.index = time_index ... Read More
When working with datetime data in Pandas, you often need to separate date and time components into different columns. This is useful for data analysis, filtering, and visualization purposes. Using the dt Accessor (Recommended) The most efficient approach is using Pandas' dt accessor to extract date and time components directly ? import pandas as pd # Create sample DataFrame with datetime column df = pd.DataFrame({'datetime': pd.date_range('2020-01-01 07:00', periods=6)}) print("Original DataFrame:") print(df) # Extract date and time using dt accessor df['date'] = df['datetime'].dt.date df['time'] = df['datetime'].dt.time print("After separating date and time:") print(df) ... Read More
Write a program in Python to print numeric index array with sorted distinct values in a given series
When working with pandas Series, you often need to convert categorical data into numeric indices. The pd.factorize() function creates numeric indices for distinct values, with an option to sort the unique values alphabetically. Understanding pd.factorize() The pd.factorize() function returns two arrays: codes − numeric indices for each element uniques − array of distinct values Without Sorting By default, pd.factorize() assigns indices based on the order of first appearance ? import pandas as pd fruits = ['mango', 'orange', 'apple', 'orange', 'mango', 'kiwi', 'pomegranate'] index, unique_values = pd.factorize(fruits) print("Without sorting of ... Read More
A rolling window calculation computes statistics over a sliding window of fixed size. In pandas, you can calculate the average of a rolling window using the rolling() method with mean(). What is Rolling Window? A rolling window of size 3 means we calculate the average of the current row and the previous 2 rows. For the first few rows where we don't have enough previous data, the result will be NaN. Creating Sample DataFrame Let's create a sample DataFrame to demonstrate rolling window calculations ? import pandas as pd df = pd.DataFrame({ ... Read More
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Economics & Finance