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
Python Articles
Page 133 of 855
Write a Python code to filter palindrome names in a given dataframe
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 MoreWrite a program in Python to localize Asian timezone for a given dataframe
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 MoreWrite a program to separate date and time from the datetime column in Python Pandas
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 MoreWrite 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 MoreWrite a program in Python to perform average of rolling window size 3 calculation in a given dataframe
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 MoreWrite a program in Python to slice substrings from each element in a given series
In Pandas, you can slice substrings from each element in a Series using string methods. This is useful for extracting specific characters or patterns from text data. Creating a Sample Series Let's start by creating a Series with fruit names ? import pandas as pd data = pd.Series(['Apple', 'Orange', 'Mango', 'Kiwis']) print("Original Series:") print(data) Original Series: 0 Apple 1 Orange 2 Mango 3 Kiwis dtype: object Method 1: Using str.slice() The str.slice() method allows ...
Read MoreHow can augmentation be used to reduce overfitting using Tensorflow and Python?
Data augmentation is a powerful technique to reduce overfitting in neural networks by artificially expanding the training dataset. When training data is limited, models tend to memorize specific details rather than learning generalizable patterns, leading to poor performance on new data. Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks? What is Data Augmentation? Data augmentation generates additional training examples by applying random transformations to existing images. These transformations include horizontal flips, rotations, and zooms that create believable variations while preserving the original class labels. Understanding Overfitting When training ...
Read MoreHow can Tensorflow be used to visualize training results using Python?
TensorFlow training results can be effectively visualized using Python with the matplotlib library. This visualization helps identify training patterns, overfitting, and model performance trends during the training process. Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks? We will use the Keras Sequential API, which is helpful in building a sequential model that works with a plain stack of layers, where every layer has exactly one input tensor and one output tensor. A neural network that contains at least one convolutional layer is known as a Convolutional Neural Network (CNN). We ...
Read MoreWrite a Python function to split the string based on delimiter and convert to series
When working with strings in Python, you often need to split them based on a delimiter and convert the result into a Pandas Series for further data analysis. This is commonly done when processing CSV-like data or text files. Understanding the Problem Let's say we have a tab-separated string like 'apple\torange\tmango\tkiwi' and want to split it into individual elements, then convert to a Pandas Series ? 0 apple 1 orange 2 mango 3 kiwi dtype: object Method 1: Using a Function ...
Read MoreWrite a program in Python to print the first and last three days from a given time series data
When working with time series data in Pandas, you often need to extract specific time periods. The first() and last() methods allow you to retrieve data from the beginning and end of a time series based on a time offset. Creating Time Series Data First, let's create a time series with city names indexed by dates ? import pandas as pd # Create a series with city names data = pd.Series(['Chennai', 'Delhi', 'Mumbai', 'Pune', 'Kolkata']) # Create a date range with 2-day frequency time_series = pd.date_range('2020-01-01', periods=5, freq='2D') # Set the date range ...
Read More