Python - Pandas

Python - Pandas

Python Pandas

Introduction

Pandas is a powerful and widely-used open-source library in Python that provides high-level data structures and tools designed to make data analysis and manipulation fast and easy. It is especially well-suited for working with structured data, such as tables, spreadsheets, and SQL databases. Built on top of NumPy, Pandas enables rich data operations with convenient indexing, grouping, filtering, merging, and time series capabilities.

Installing and Importing Pandas

Installation

pip install pandas

Importing the Library

import pandas as pd

Core Data Structures in Pandas

Series

A Series is a one-dimensional labeled array capable of holding any data type.

import pandas as pd

s = pd.Series([10, 20, 30, 40])
print(s)

DataFrame

A DataFrame is a two-dimensional labeled data structure with columns of potentially different types.

data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'Salary': [50000, 60000, 70000]
}

df = pd.DataFrame(data)
print(df)

Creating DataFrames

From Dictionary

data = {
    'Product': ['Apple', 'Banana', 'Mango'],
    'Price': [100, 40, 60]
}
df = pd.DataFrame(data)
print(df)

From Lists

data = [['Tom', 25], ['Jerry', 30]]
df = pd.DataFrame(data, columns=['Name', 'Age'])
print(df)

From CSV File

df = pd.read_csv('data.csv')
print(df.head())

Data Inspection

Head and Tail

print(df.head())     # First 5 rows
print(df.tail())     # Last 5 rows

Shape and Info

print(df.shape)
print(df.info())

Summary Statistics

print(df.describe())

Indexing and Selection

Accessing Columns

print(df['Name'])

Accessing Rows

print(df.loc[0])     # Access by label
print(df.iloc[0])    # Access by position

Slicing

print(df[1:3])

Data Manipulation

Adding Columns

df['Tax'] = df['Salary'] * 0.1
print(df)

Renaming Columns

df.rename(columns={'Salary': 'Income'}, inplace=True)
print(df)

Dropping Columns and Rows

df.drop('Tax', axis=1, inplace=True)      # Drop column
df.drop(1, axis=0, inplace=True)          # Drop row

Filtering Data

print(df[df['Age'] > 28])

Changing Data Types

df['Age'] = df['Age'].astype(float)

Handling Missing Data

Detecting Missing Data

print(df.isnull())
print(df.isnull().sum())

Filling Missing Values

df.fillna(value=0, inplace=True)

Dropping Missing Values

df.dropna(inplace=True)

Data Aggregation

GroupBy Operations

grouped = df.groupby('Age')
print(grouped['Income'].mean())

Aggregation Functions

print(df.agg({'Income': ['sum', 'mean'], 'Age': ['min', 'max']}))

Merging, Joining, and Concatenating

Concatenation

df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})

result = pd.concat([df1, df2])
print(result)

Merge

df1 = pd.DataFrame({'key': ['K0', 'K1'], 'A': ['A0', 'A1']})
df2 = pd.DataFrame({'key': ['K0', 'K1'], 'B': ['B0', 'B1']})

merged = pd.merge(df1, df2, on='key')
print(merged)

Join

df1 = df1.set_index('key')
df2 = df2.set_index('key')

joined = df1.join(df2)
print(joined)

Sorting and Ranking

Sorting by Values

df.sort_values(by='Age', ascending=False, inplace=True)
print(df)

Sorting by Index

df.sort_index(inplace=True)

Ranking

df['Rank'] = df['Income'].rank()
print(df)

Working with Dates and Times

Creating DateTime Objects

df['JoinDate'] = pd.to_datetime(['2023-01-01', '2023-02-15', '2023-03-01'])

Extracting Date Components

df['Year'] = df['JoinDate'].dt.year
df['Month'] = df['JoinDate'].dt.month

Filtering by Date

print(df[df['JoinDate'] > '2023-01-31'])

Reading and Writing Files

Read CSV

df = pd.read_csv('data.csv')

Write CSV

df.to_csv('output.csv', index=False)

Read Excel

df = pd.read_excel('data.xlsx')

Write Excel

df.to_excel('output.xlsx', index=False)

Pivot Tables

Basic Pivot Table

pivot = df.pivot_table(values='Income', index='Age', aggfunc='mean')
print(pivot)

Visualization with Pandas

Line Plot

df.plot(x='Age', y='Income', kind='line')

Bar Plot

df.plot(x='Name', y='Income', kind='bar')

Histogram

df['Age'].plot(kind='hist')

Advanced Topics

MultiIndex DataFrames

arrays = [['bar', 'bar', 'baz'], ['one', 'two', 'three']]
index = pd.MultiIndex.from_arrays(arrays, names=('first', 'second'))
df = pd.DataFrame({'A': [1, 2, 3]}, index=index)
print(df)

Reshaping with Stack and Unstack

df_unstacked = df.unstack()
df_stacked = df_unstacked.stack()

Window Functions

df['RollingMean'] = df['Income'].rolling(window=2).mean()
print(df)

Pandas is a cornerstone tool in the Python data science ecosystem. It provides intuitive, flexible, and efficient methods for data analysis and preprocessing, enabling rapid insights and modeling. With features such as powerful indexing, missing data handling, groupby and aggregation, file I/O, and time series support, Pandas is indispensable for both beginners and professionals working with real-world data.

Learning Pandas thoroughly equips you to handle almost any kind of tabular data manipulation or analysis task in Python. As you continue exploring, combining Pandas with libraries like NumPy, matplotlib, seaborn, and scikit-learn will further expand your data science capabilities.

logo

Python

Beginner 5 Hours
Python - Pandas

Python Pandas

Introduction

Pandas is a powerful and widely-used open-source library in Python that provides high-level data structures and tools designed to make data analysis and manipulation fast and easy. It is especially well-suited for working with structured data, such as tables, spreadsheets, and SQL databases. Built on top of NumPy, Pandas enables rich data operations with convenient indexing, grouping, filtering, merging, and time series capabilities.

Installing and Importing Pandas

Installation

pip install pandas

Importing the Library

import pandas as pd

Core Data Structures in Pandas

Series

A Series is a one-dimensional labeled array capable of holding any data type.

import pandas as pd s = pd.Series([10, 20, 30, 40]) print(s)

DataFrame

A DataFrame is a two-dimensional labeled data structure with columns of potentially different types.

data = { 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'Salary': [50000, 60000, 70000] } df = pd.DataFrame(data) print(df)

Creating DataFrames

From Dictionary

data = { 'Product': ['Apple', 'Banana', 'Mango'], 'Price': [100, 40, 60] } df = pd.DataFrame(data) print(df)

From Lists

data = [['Tom', 25], ['Jerry', 30]] df = pd.DataFrame(data, columns=['Name', 'Age']) print(df)

From CSV File

df = pd.read_csv('data.csv') print(df.head())

Data Inspection

Head and Tail

print(df.head()) # First 5 rows print(df.tail()) # Last 5 rows

Shape and Info

print(df.shape) print(df.info())

Summary Statistics

print(df.describe())

Indexing and Selection

Accessing Columns

print(df['Name'])

Accessing Rows

print(df.loc[0]) # Access by label print(df.iloc[0]) # Access by position

Slicing

print(df[1:3])

Data Manipulation

Adding Columns

df['Tax'] = df['Salary'] * 0.1 print(df)

Renaming Columns

df.rename(columns={'Salary': 'Income'}, inplace=True) print(df)

Dropping Columns and Rows

df.drop('Tax', axis=1, inplace=True) # Drop column df.drop(1, axis=0, inplace=True) # Drop row

Filtering Data

print(df[df['Age'] > 28])

Changing Data Types

df['Age'] = df['Age'].astype(float)

Handling Missing Data

Detecting Missing Data

print(df.isnull()) print(df.isnull().sum())

Filling Missing Values

df.fillna(value=0, inplace=True)

Dropping Missing Values

df.dropna(inplace=True)

Data Aggregation

GroupBy Operations

grouped = df.groupby('Age') print(grouped['Income'].mean())

Aggregation Functions

print(df.agg({'Income': ['sum', 'mean'], 'Age': ['min', 'max']}))

Merging, Joining, and Concatenating

Concatenation

df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]}) result = pd.concat([df1, df2]) print(result)

Merge

df1 = pd.DataFrame({'key': ['K0', 'K1'], 'A': ['A0', 'A1']}) df2 = pd.DataFrame({'key': ['K0', 'K1'], 'B': ['B0', 'B1']}) merged = pd.merge(df1, df2, on='key') print(merged)

Join

df1 = df1.set_index('key') df2 = df2.set_index('key') joined = df1.join(df2) print(joined)

Sorting and Ranking

Sorting by Values

df.sort_values(by='Age', ascending=False, inplace=True) print(df)

Sorting by Index

df.sort_index(inplace=True)

Ranking

df['Rank'] = df['Income'].rank() print(df)

Working with Dates and Times

Creating DateTime Objects

df['JoinDate'] = pd.to_datetime(['2023-01-01', '2023-02-15', '2023-03-01'])

Extracting Date Components

df['Year'] = df['JoinDate'].dt.year df['Month'] = df['JoinDate'].dt.month

Filtering by Date

print(df[df['JoinDate'] > '2023-01-31'])

Reading and Writing Files

Read CSV

df = pd.read_csv('data.csv')

Write CSV

df.to_csv('output.csv', index=False)

Read Excel

df = pd.read_excel('data.xlsx')

Write Excel

df.to_excel('output.xlsx', index=False)

Pivot Tables

Basic Pivot Table

pivot = df.pivot_table(values='Income', index='Age', aggfunc='mean') print(pivot)

Visualization with Pandas

Line Plot

df.plot(x='Age', y='Income', kind='line')

Bar Plot

df.plot(x='Name', y='Income', kind='bar')

Histogram

df['Age'].plot(kind='hist')

Advanced Topics

MultiIndex DataFrames

arrays = [['bar', 'bar', 'baz'], ['one', 'two', 'three']] index = pd.MultiIndex.from_arrays(arrays, names=('first', 'second')) df = pd.DataFrame({'A': [1, 2, 3]}, index=index) print(df)

Reshaping with Stack and Unstack

df_unstacked = df.unstack() df_stacked = df_unstacked.stack()

Window Functions

df['RollingMean'] = df['Income'].rolling(window=2).mean() print(df)

Pandas is a cornerstone tool in the Python data science ecosystem. It provides intuitive, flexible, and efficient methods for data analysis and preprocessing, enabling rapid insights and modeling. With features such as powerful indexing, missing data handling, groupby and aggregation, file I/O, and time series support, Pandas is indispensable for both beginners and professionals working with real-world data.

Learning Pandas thoroughly equips you to handle almost any kind of tabular data manipulation or analysis task in Python. As you continue exploring, combining Pandas with libraries like NumPy, matplotlib, seaborn, and scikit-learn will further expand your data science capabilities.

Frequently Asked Questions for Python

Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.


Python's syntax is a lot closer to English and so it is easier to read and write, making it the simplest type of code to learn how to write and develop with. The readability of C++ code is weak in comparison and it is known as being a language that is a lot harder to get to grips with.

Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works. Performance: Java has a higher performance than Python due to its static typing and optimization by the Java Virtual Machine (JVM).

Python can be considered beginner-friendly, as it is a programming language that prioritizes readability, making it easier to understand and use. Its syntax has similarities with the English language, making it easy for novice programmers to leap into the world of development.

To start coding in Python, you need to install Python and set up your development environment. You can download Python from the official website, use Anaconda Python, or start with DataLab to get started with Python in your browser.

Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.

Python alone isn't going to get you a job unless you are extremely good at it. Not that you shouldn't learn it: it's a great skill to have since python can pretty much do anything and coding it is fast and easy. It's also a great first programming language according to lots of programmers.

The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.


Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.


6 Top Tips for Learning Python

  • Choose Your Focus. Python is a versatile language with a wide range of applications, from web development and data analysis to machine learning and artificial intelligence.
  • Practice regularly.
  • Work on real projects.
  • Join a community.
  • Don't rush.
  • Keep iterating.

The following is a step-by-step guide for beginners interested in learning Python using Windows.

  • Set up your development environment.
  • Install Python.
  • Install Visual Studio Code.
  • Install Git (optional)
  • Hello World tutorial for some Python basics.
  • Hello World tutorial for using Python with VS Code.

Best YouTube Channels to Learn Python

  • Corey Schafer.
  • sentdex.
  • Real Python.
  • Clever Programmer.
  • CS Dojo (YK)
  • Programming with Mosh.
  • Tech With Tim.
  • Traversy Media.

Python can be written on any computer or device that has a Python interpreter installed, including desktop computers, servers, tablets, and even smartphones. However, a laptop or desktop computer is often the most convenient and efficient option for coding due to its larger screen, keyboard, and mouse.

Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.

  • Google's Python Class.
  • Microsoft's Introduction to Python Course.
  • Introduction to Python Programming by Udemy.
  • Learn Python - Full Course for Beginners by freeCodeCamp.
  • Learn Python 3 From Scratch by Educative.
  • Python for Everybody by Coursera.
  • Learn Python 2 by Codecademy.

  • Understand why you're learning Python. Firstly, it's important to figure out your motivations for wanting to learn Python.
  • Get started with the Python basics.
  • Master intermediate Python concepts.
  • Learn by doing.
  • Build a portfolio of projects.
  • Keep challenging yourself.

Top 5 Python Certifications - Best of 2024
  • PCEP (Certified Entry-level Python Programmer)
  • PCAP (Certified Associate in Python Programmer)
  • PCPP1 & PCPP2 (Certified Professional in Python Programming 1 & 2)
  • Certified Expert in Python Programming (CEPP)
  • Introduction to Programming Using Python by Microsoft.

The average salary for Python Developer is β‚Ή5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from β‚Ή3,000 - β‚Ή1,20,000.

The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python website, https://www.python.org/, and may be freely distributed.

If you're looking for a lucrative and in-demand career path, you can't go wrong with Python. As one of the fastest-growing programming languages in the world, Python is an essential tool for businesses of all sizes and industries. Python is one of the most popular programming languages in the world today.

line

Copyrights © 2024 letsupdateskills All rights reserved