HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat N Strings
      • Python Example Code to Concat 2 Numbers
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
    • Modules and Libraries
      • Python Code to Load .SO File (and Invoke a Function)
      • Python Code for Automation using BDD
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Python Code to Perform Data Analysis with Pandas

Pandas is a powerful library in Python designed for data manipulation and analysis. It provides data structures like DataFrames and Series, which make it easy to handle and analyze large datasets.

With Pandas, you can perform a wide range of operations on data, from basic filtering to complex transformations.

The library is highly flexible and integrates well with other data analysis tools. It allows you to read data from various formats, including CSV, Excel, and SQL databases. Pandas also offers robust functionalities for data cleaning, merging, and aggregation.

Using Pandas, you can quickly summarize data and generate insights. Its intuitive functions and methods streamline tasks such as statistical analysis and data visualization. This makes Pandas an essential tool for anyone working with data in Python.

Prerequisites

Ensure you have Pandas installed. You can install it using pip:

pip install pandas

Python Code Example

Here is a Python script that performs data analysis using Pandas:

import pandas as pd

# Sample data
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
    'Age': [24, 27, 22, 32, 29],
    'Salary': [50000, 54000, 58000, 60000, 62000]
}

# Create DataFrame
df = pd.DataFrame(data)

# Display the DataFrame
print("DataFrame:")
print(df)

# Calculate basic statistics
mean_age = df['Age'].mean()
median_salary = df['Salary'].median()

# Display statistics
print("\nStatistics:")
print(f"Mean Age: {mean_age}")
print(f"Median Salary: {median_salary}")

# Filter data
high_earners = df[df['Salary'] > 55000]

# Display filtered data
print("\nHigh Earners:")
print(high_earners)

Output Example

The output of the script will display the DataFrame, calculated statistics, and filtered data. Here is a sample of the output:

DataFrame:
      Name  Age  Salary
0    Alice   24   50000
1      Bob   27   54000
2  Charlie   22   58000
3    David   32   60000
4      Eva   29   62000

Statistics:
Mean Age: 26.4
Median Salary: 58000.0

High Earners:
      Name  Age  Salary
2  Charlie   22   58000
3    David   32   60000
4      Eva   29   62000

Explanation of the Code

  • import pandas as pd: Import the Pandas library for data manipulation.
  • data: Define a dictionary with sample data including names, ages, and salaries.
  • pd.DataFrame(data): Create a DataFrame from the dictionary.
  • df['Age'].mean(): Calculate the mean age of the individuals in the DataFrame.
  • df['Salary'].median(): Calculate the median salary of the individuals.
  • df[df['Salary'] > 55000]: Filter the DataFrame to include only those with a salary greater than 55,000.
  • print(df), print(f"Mean Age: {mean_age}"), print(high_earners): Display the DataFrame, calculated statistics, and filtered data.

Uses of Pandas in Python

  1. Data Cleaning: Pandas helps you clean and preprocess data by handling missing values, removing duplicates, and correcting data types.
  2. Data Transformation: You can transform data with ease. This includes filtering rows, applying functions, and transforming data structures.
  3. Data Aggregation: Pandas allows you to summarize data using operations like grouping and aggregating. This helps in calculating statistics such as sums, means, and counts.
  4. Data Merging: Combining multiple datasets is simple with Pandas. Use functions like merge() and concat() to join tables based on common columns or indices.
  5. Data Visualization: While Pandas itself has basic plotting capabilities, it integrates well with libraries like Matplotlib for creating advanced visualizations.
  6. Data Analysis: Perform detailed data analysis by applying statistical methods and performing operations like pivot tables and cross-tabulations.
  7. Reading/Writing Data: Pandas can read from and write to various file formats, including CSV, Excel, JSON, and SQL databases, making it easy to handle different data sources.
  8. Time Series Analysis: Pandas provides robust tools for working with time series data, including resampling, rolling windows, and date range generation.
  9. Exploratory Data Analysis (EDA): Use Pandas for initial exploration of data. You can quickly view data summaries and detect patterns or anomalies.
  10. Handling Large Datasets: Pandas is optimized for performance with large datasets. It offers efficient operations for handling and processing data without excessive memory usage.

Pandas provides a versatile and powerful way to perform data analysis in Python. By using DataFrames and various methods, you can efficiently analyze and manipulate your data.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Example Python Code to Plot Data Using Matplotlib

No luck finding what you need? Contact Us

Previously
Example Python Code to Plot Data Using Matplotlib
Up Next
Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.