This document provides an overview of Python libraries for data analysis and data science. It discusses popular Python libraries such as NumPy, Pandas, SciPy, Scikit-Learn and visualization libraries like matplotlib and Seaborn. It describes the functionality of these libraries for tasks like reading and manipulating data, descriptive statistics, inferential statistics, machine learning and data visualization. It also provides examples of using these libraries to explore a sample dataset and perform operations like data filtering, aggregation, grouping and missing value handling.
Best Data Science Ppt using Python
Data science is an inter-disciplinary field that uses scientific methods, processes, algorithms and systems to extract knowledge and insights from many structural and unstructured data. Data science is related to data mining, machine learning and big data.
The document discusses various Python libraries used for data science tasks. It describes NumPy for numerical computing, SciPy for algorithms, Pandas for data structures and analysis, Scikit-Learn for machine learning, Matplotlib for visualization, and Seaborn which builds on Matplotlib. It also provides examples of loading data frames in Pandas, exploring and manipulating data, grouping and aggregating data, filtering, sorting, and handling missing values.
This document provides a summary of a seminar presentation on robotic process automation and virtual internships. It introduces popular Python libraries for data science like NumPy, SciPy, Pandas, matplotlib and Seaborn. It covers reading, exploring and manipulating data frames; filtering and selecting data; grouping; descriptive statistics. It also discusses missing value handling and aggregation functions. The goal is to provide an overview of key Python tools and techniques for data analysis.
Python for Data Science is a must learn for professionals in the Data Analytics domain. With the growth in IT industry, there is a booming demand for skilled Data Scientists and Python has evolved as the most preferred programming language. Through this blog, you will learn the basics, how to analyze data and then create some beautiful visualizations using Python.
This document provides an overview of popular Python libraries for data science and analysis. It discusses NumPy for efficient numerical computations, SciPy for scientific computing functions, Pandas for data structures and analysis, Scikit-Learn for machine learning algorithms, and Matplotlib and Seaborn for data visualization. It also describes common operations in Pandas like reading data, selecting and filtering data, descriptive statistics, and grouping data.
This document provides an overview of popular Python libraries for data science, including NumPy, SciPy, Pandas, Scikit-Learn, matplotlib and Seaborn. It describes the main functions of each library, such as NumPy for multidimensional arrays and mathematical operations, Pandas for data structures and data manipulation, Scikit-Learn for machine learning algorithms, and matplotlib and Seaborn for data visualization. The document also covers reading and exploring data frames, selecting and filtering data, aggregating and grouping data, handling missing values, and basic statistical analysis and graphics.
This document provides an overview of popular Python libraries for data science and analysis. It discusses NumPy for efficient numerical computations, SciPy for scientific computing functions, Pandas for data structures and manipulation, Scikit-Learn for machine learning algorithms, and Matplotlib and Seaborn for data visualization. It also describes common operations in Pandas like reading data, exploring data frames, selecting columns and rows, filtering, grouping, and descriptive statistics.
This document provides an overview of popular Python libraries for data science, including NumPy, SciPy, Pandas, Scikit-Learn, matplotlib and Seaborn. It describes what each library is used for, such as NumPy for multidimensional arrays and mathematical operations, Pandas for data manipulation and analysis, and Scikit-Learn for machine learning algorithms. It also discusses reading and exploring data frames, selecting and filtering data, aggregating and grouping data, handling missing values, and data visualization.
This document provides an introduction to data analysis techniques using Python. It discusses key Python libraries for data analysis like NumPy, Pandas, SciPy, Scikit-Learn and libraries for data visualization like matplotlib and Seaborn. It covers essential concepts in data analysis like Series, DataFrames and how to perform data cleaning, transformation, aggregation and visualization on data frames. It also discusses statistical analysis, machine learning techniques and how big data and data analytics can work together. The document is intended as an overview and hands-on guide to getting started with data analysis in Python.
The document provides an overview of popular Python libraries for data science such as NumPy, SciPy, Pandas, SciKit-Learn, matplotlib, and Seaborn. It discusses the key features and uses of each library. The document also demonstrates how to load data into Pandas data frames, explore and manipulate the data frames using various methods like head(), groupby(), filtering, and slicing. Summary statistics, plotting and other analyses can be performed on the data frames using these libraries.
Vectorization refers to performing operations on entire NumPy arrays or sequences of data without using explicit loops. This allows computations to be performed more efficiently by leveraging optimized low-level code. Traditional Python code may use loops to perform operations element-wise, whereas NumPy allows the same operations to be performed vectorized on entire arrays. Broadcasting rules allow operations between arrays of different shapes by automatically expanding dimensions. Vectorization is a key technique for speeding up numerical Python code using NumPy.
This document provides an overview of a machine learning course that teaches Pandas basics. The course aims to teach students how to handle and visualize data, apply basic learning algorithms, develop supervised and unsupervised learning techniques, and build machine learning models. The document outlines the course objectives, outcomes, syllabus including data preprocessing, feature extraction, and data visualization techniques. It also provides references for further reading.
Pandas Dataframe reading data Kirti final.pptxKirti Verma
Ìý
Pandas is a Python library used for data manipulation and analysis. It provides data structures like Series and DataFrames that make working with structured data easy. A DataFrame is a two-dimensional data structure that can store data of different types in columns. DataFrames can be created from dictionaries, lists, CSV files, JSON files and other sources. They allow indexing, selecting, adding and deleting of rows and columns. Pandas provides useful methods for data cleaning, manipulation and analysis tasks on DataFrames.
1. NumPy is a fundamental Python library for numerical computing that provides support for arrays and vectorized computations.
2. Pandas is a popular Python library for data manipulation and analysis that provides DataFrame and Series data structures to work with tabular data.
3. When performing arithmetic operations between DataFrames or Series in Pandas, the data is automatically aligned based on index and column labels to maintain data integrity. NumPy also automatically broadcasts arrays during arithmetic to align dimensions element-wise.
This document provides an overview of working with DataFrames in Python using the Pandas library. It discusses:
1. What a DataFrame is - a two-dimensional, size-mutable, tabular data structure in Pandas for data manipulation.
2. How to create DataFrames from dictionaries, lists, CSV files and more.
3. Common tasks like viewing data, selecting rows/columns, modifying data, analysis and saving DataFrames.
It also covers indexing and filtering DataFrames using labels or boolean conditions, arithmetic alignment in Pandas and NumPy, and vectorized computation in NumPy.
XII - 2022-23 - IP - RAIPUR (CBSE FINAL EXAM).pdfKrishnaJyotish1
Ìý
The document provides study material and sample papers for Class XII students of Kendriya Vidyalaya Sangathan Regional Office Raipur for the 2022-23 session. It lists the subject coordination by Mrs. Sandhya Lakra, Principal of KV No. 4 Korba and the content team comprising of 7 PGT Computer Science teachers from different KVs. The compilation, review and vetting is done by Mr. Sumit Kumar Choudhary, PGT CS of KV No. 2 Korba NTPC. The document contains introduction and concepts related to data handling using Pandas and Matplotlib libraries in Python.
pandasppt with informative topics coverage.pptxvallarasu200364
Ìý
Pandas is a Python library used for working with structured and unstructured data. It allows users to load, clean, transform, and analyze data. Pandas provides data structures like Series (1D) and DataFrames (2D) that make it easy to manipulate data. DataFrames act like a dictionary of Series and support indexing, slicing, and selection like NumPy arrays. This allows convenient data retrieval and manipulation.
Unit 4_Working with Graphs _python (2).pptxprakashvs7
Ìý
The document discusses various techniques for string manipulation in Python. It covers common string operations like concatenation, slicing, searching, replacing, formatting, splitting, stripping whitespace, and case conversion. Specific methods and functions are provided for each technique using Python's built-in string methods. Examples are given to demonstrate how to use string manipulation methods like find(), replace(), split(), strip(), lower(), upper(), etc. to perform various string operations in Python.
This document discusses various methods for importing, exporting, and summarizing data in Python using the Pandas library. It covers reading and writing CSV, TXT, and XLSX files with Pandas, checking the structure and dimensions of data frames, handling missing values, and modifying data through functions like rename(). The key methods described are read_csv(), read_table(), read_excel(), to_csv(), info(), isnull(), sum(), head(), tail(), and describe().
fINAL Lesson_5_Data_Manipulation_using_R_v1.pptxdataKarthik
Ìý
Anna is a junior data scientist working on a customer retention strategy. She needs to analyze data from different sources to understand customer value. To efficiently perform her job, she needs to learn techniques for reading, merging, summarizing and preparing data for analysis in R. These include reading data from files and databases, merging tables, summarizing data using functions like mean, median, and aggregate, and exporting cleaned data.
The document discusses various methods for reading data into R from different sources:
- CSV files can be read using read.csv()
- Excel files can be read using the readxl package
- SAS, Stata, and SPSS files can be imported using the haven package functions read_sas(), read_dta(), and read_sav() respectively
- SAS files with the .sas7bdat extension can also be read using the sas7bdat package
Pandas is an open source Python library that provides data structures and data analysis tools for working with tabular data. It allows users to easily perform operations on different types of data such as tabular, time series, and matrix data. Pandas provides data structures like Series for 1D data and DataFrame for 2D data. It has tools for data cleaning, transformation, manipulation, and visualization of data.
This document provides an overview of popular Python libraries for data science and analysis. It discusses NumPy for efficient numerical computations, SciPy for scientific computing functions, Pandas for data structures and manipulation, Scikit-Learn for machine learning algorithms, and Matplotlib and Seaborn for data visualization. It also describes common operations in Pandas like reading data, exploring data frames, selecting columns and rows, filtering, grouping, and descriptive statistics.
This document provides an overview of popular Python libraries for data science, including NumPy, SciPy, Pandas, Scikit-Learn, matplotlib and Seaborn. It describes what each library is used for, such as NumPy for multidimensional arrays and mathematical operations, Pandas for data manipulation and analysis, and Scikit-Learn for machine learning algorithms. It also discusses reading and exploring data frames, selecting and filtering data, aggregating and grouping data, handling missing values, and data visualization.
This document provides an introduction to data analysis techniques using Python. It discusses key Python libraries for data analysis like NumPy, Pandas, SciPy, Scikit-Learn and libraries for data visualization like matplotlib and Seaborn. It covers essential concepts in data analysis like Series, DataFrames and how to perform data cleaning, transformation, aggregation and visualization on data frames. It also discusses statistical analysis, machine learning techniques and how big data and data analytics can work together. The document is intended as an overview and hands-on guide to getting started with data analysis in Python.
The document provides an overview of popular Python libraries for data science such as NumPy, SciPy, Pandas, SciKit-Learn, matplotlib, and Seaborn. It discusses the key features and uses of each library. The document also demonstrates how to load data into Pandas data frames, explore and manipulate the data frames using various methods like head(), groupby(), filtering, and slicing. Summary statistics, plotting and other analyses can be performed on the data frames using these libraries.
Vectorization refers to performing operations on entire NumPy arrays or sequences of data without using explicit loops. This allows computations to be performed more efficiently by leveraging optimized low-level code. Traditional Python code may use loops to perform operations element-wise, whereas NumPy allows the same operations to be performed vectorized on entire arrays. Broadcasting rules allow operations between arrays of different shapes by automatically expanding dimensions. Vectorization is a key technique for speeding up numerical Python code using NumPy.
This document provides an overview of a machine learning course that teaches Pandas basics. The course aims to teach students how to handle and visualize data, apply basic learning algorithms, develop supervised and unsupervised learning techniques, and build machine learning models. The document outlines the course objectives, outcomes, syllabus including data preprocessing, feature extraction, and data visualization techniques. It also provides references for further reading.
Pandas Dataframe reading data Kirti final.pptxKirti Verma
Ìý
Pandas is a Python library used for data manipulation and analysis. It provides data structures like Series and DataFrames that make working with structured data easy. A DataFrame is a two-dimensional data structure that can store data of different types in columns. DataFrames can be created from dictionaries, lists, CSV files, JSON files and other sources. They allow indexing, selecting, adding and deleting of rows and columns. Pandas provides useful methods for data cleaning, manipulation and analysis tasks on DataFrames.
1. NumPy is a fundamental Python library for numerical computing that provides support for arrays and vectorized computations.
2. Pandas is a popular Python library for data manipulation and analysis that provides DataFrame and Series data structures to work with tabular data.
3. When performing arithmetic operations between DataFrames or Series in Pandas, the data is automatically aligned based on index and column labels to maintain data integrity. NumPy also automatically broadcasts arrays during arithmetic to align dimensions element-wise.
This document provides an overview of working with DataFrames in Python using the Pandas library. It discusses:
1. What a DataFrame is - a two-dimensional, size-mutable, tabular data structure in Pandas for data manipulation.
2. How to create DataFrames from dictionaries, lists, CSV files and more.
3. Common tasks like viewing data, selecting rows/columns, modifying data, analysis and saving DataFrames.
It also covers indexing and filtering DataFrames using labels or boolean conditions, arithmetic alignment in Pandas and NumPy, and vectorized computation in NumPy.
XII - 2022-23 - IP - RAIPUR (CBSE FINAL EXAM).pdfKrishnaJyotish1
Ìý
The document provides study material and sample papers for Class XII students of Kendriya Vidyalaya Sangathan Regional Office Raipur for the 2022-23 session. It lists the subject coordination by Mrs. Sandhya Lakra, Principal of KV No. 4 Korba and the content team comprising of 7 PGT Computer Science teachers from different KVs. The compilation, review and vetting is done by Mr. Sumit Kumar Choudhary, PGT CS of KV No. 2 Korba NTPC. The document contains introduction and concepts related to data handling using Pandas and Matplotlib libraries in Python.
pandasppt with informative topics coverage.pptxvallarasu200364
Ìý
Pandas is a Python library used for working with structured and unstructured data. It allows users to load, clean, transform, and analyze data. Pandas provides data structures like Series (1D) and DataFrames (2D) that make it easy to manipulate data. DataFrames act like a dictionary of Series and support indexing, slicing, and selection like NumPy arrays. This allows convenient data retrieval and manipulation.
Unit 4_Working with Graphs _python (2).pptxprakashvs7
Ìý
The document discusses various techniques for string manipulation in Python. It covers common string operations like concatenation, slicing, searching, replacing, formatting, splitting, stripping whitespace, and case conversion. Specific methods and functions are provided for each technique using Python's built-in string methods. Examples are given to demonstrate how to use string manipulation methods like find(), replace(), split(), strip(), lower(), upper(), etc. to perform various string operations in Python.
This document discusses various methods for importing, exporting, and summarizing data in Python using the Pandas library. It covers reading and writing CSV, TXT, and XLSX files with Pandas, checking the structure and dimensions of data frames, handling missing values, and modifying data through functions like rename(). The key methods described are read_csv(), read_table(), read_excel(), to_csv(), info(), isnull(), sum(), head(), tail(), and describe().
fINAL Lesson_5_Data_Manipulation_using_R_v1.pptxdataKarthik
Ìý
Anna is a junior data scientist working on a customer retention strategy. She needs to analyze data from different sources to understand customer value. To efficiently perform her job, she needs to learn techniques for reading, merging, summarizing and preparing data for analysis in R. These include reading data from files and databases, merging tables, summarizing data using functions like mean, median, and aggregate, and exporting cleaned data.
The document discusses various methods for reading data into R from different sources:
- CSV files can be read using read.csv()
- Excel files can be read using the readxl package
- SAS, Stata, and SPSS files can be imported using the haven package functions read_sas(), read_dta(), and read_sav() respectively
- SAS files with the .sas7bdat extension can also be read using the sas7bdat package
Pandas is an open source Python library that provides data structures and data analysis tools for working with tabular data. It allows users to easily perform operations on different types of data such as tabular, time series, and matrix data. Pandas provides data structures like Series for 1D data and DataFrame for 2D data. It has tools for data cleaning, transformation, manipulation, and visualization of data.
CloudMonitor - Architecture Audit Review February 2025.pdfRodney Joyce
Ìý
CloudMonitor FinOps is now a Microsoft Certified solution in the Azure Marketplace. This little badge means that we passed a 3rd-party Technical Audit as well as met various sales KPIs and milestones over the last 12 months.
We used our existing Architecture docs for CISOs and Cloud Architects to craft an Audit Response - I've shared it below to help others obtain their cert.
Interestingly, 90% of our customers are in the USA, with very few in Australia. This is odd as the first thing I hear in every meetup and conference, from partners, customers and Microsoft, is that they want to optimise their cloud spend! But very few Australian companies are using the FinOps Framework to lower Azure costs.
Relationship between Happiness & LifeQuality .pdfwrachelsong
Ìý
There a lot of studies showing the correlation between GDP by country and average life satisfcation. Usually, most countries with higher GDP tend to have higher average life satisfaction scores. Inspired by this findings, I began to wonder.. 'What other aspects of life significantly contribute to happiness?' Specifically, we wanted to explore which quality of life indicators have a significant relationship with the happiness scores of different regions.
Research Question : Which quality of life indicators have a significant relationship with the happiness score among different regions?
To address this question, we decided to investigate various factors that might influence happiness, including economic stability, health, social support, and more.
Valkey 101 - SCaLE 22x March 2025 Stokes.pdfDave Stokes
Ìý
An Introduction to Valkey, Presented March 2025 at the Southern California Linux Expo, Pasadena CA. Valkey is a replacement for Redis and is a very fast in memory database, used to caches and other low latency applications. Valkey is open-source software and very fast.
RAGing Against the Literature: LLM-Powered Dataset Mention Extraction-present...suchanadatta3
Ìý
Dataset Mention Extraction (DME) is a critical task in the field of scientific information extraction, aiming to identify references
to datasets within research papers. In this paper, we explore two advanced methods for DME from research papers, utilizing the
capabilities of Large Language Models (LLMs). The first method
employs a language model with a prompt-based framework to ex-
tract dataset names from text chunks, utilizing patterns of dataset mentions as guidance. The second method integrates the Retrieval-Augmented Generation (RAG) framework, which enhances dataset extraction through a combination of keyword-based filtering, semantic retrieval, and iterative refinement.
Deep-QPP: A Pairwise Interaction-based Deep Learning Model for Supervised Que...suchanadatta3
Ìý
Motivated by the recent success of end-to-end deep neural models
for ranking tasks, we present here a supervised end-to-end neural
approach for query performance prediction (QPP). In contrast to
unsupervised approaches that rely on various statistics of document
score distributions, our approach is entirely data-driven. Further,
in contrast to weakly supervised approaches, our method also does
not rely on the outputs from different QPP estimators. In particular, our model leverages information from the semantic interactions between the terms of a query and those in the top-documents retrieved with it. The architecture of the model comprises multiple layers of 2D convolution filters followed by a feed-forward layer of parameters. Experiments on standard test collections demonstrate
that our proposed supervised approach outperforms other state-of-the-art supervised and unsupervised approaches.
Design Data Model Objects for Analytics, Activation, and AIaaronmwinters
Ìý
Explore using industry-specific data standards to design data model objects in Data Cloud that can consolidate fragmented and multi-format data sources into a single view of the customer.
Design of the data model objects is a critical first step in setting up Data Cloud and will impact aspects of the implementation, including the data harmonization and mappings, as well as downstream automations and AI processing. This session will provide concrete examples of data standards in the education space and how to design a Data Cloud data model that will hold up over the long-term as new source systems and activation targets are added to the landscape. This will help architects and business analysts accelerate adoption of Data Cloud.
Hire Android App Developers in India with Cerebraixcerebraixs
Ìý
Android app developers are crucial for creating
high-quality, user-friendly, and innovative mobile
applications. Their expertise in mobile development,
UI/UX design, and seamless integration ensures robust
and scalable apps that drive user engagement and
business success in the competitive mobile market.
AI + Disability. Coded Futures: Better opportunities or biased outcomes?Christine Hemphill
Ìý
A summary report into attitudes to and implications of AI as it relates to disability. Will AI enabled solutions create greater opportunities or amplify biases in society and datasets? Informed by primary mixed methods research conducted in the UK and globally by Open Inclusion on behalf of the Institute of People Centred AI, Uni of Surrey and Royal Holloway University. Initially presented at Google London in Jan 2025.
If you prefer an audio visual format you can access the full video recorded at Google ADC London where we presented this research in January 2025. It has captioned content and audio described visuals and is available at https://www.youtube.com/watch?v=p_1cv042U_U. There is also a short Fireside Chat about the research held at Zero Project Conference March 2025 available at https://www.youtube.com/live/oFCgIg78-mI?si=EoIaEgDw2U7DFXsN&t=11879.
If ºÝºÝߣ Share's format is not accessible to you in any way, please contact us at contact@openinclusion.com and we can provide you with the underlying document.
2. Tutorial
Content
2
Overview of Python Libraries
Reading Data; Selecting and Filtering the Data; Data manipulation,
sorting, grouping, rearranging
Plotting the data
Descriptive statistics
Inferential statistics
3. Python Libraries for Data Science
Many popular Python toolboxes/libraries:
• NumPy
• SciPy
• Pandas
• SciKit-Learn
Visualization libraries
• matplotlib
• Seaborn
and many more …
3
4. Python Libraries for Data Science
NumPy:
 introduces objects for multidimensional arrays and matrices, as well as
functions that allow to easily perform advanced mathematical and statistical
operations on those objects
 provides vectorization of mathematical operations on arrays and matrices
which significantly improves the performance
 many other python libraries are built on NumPy
4
Link: http://www.numpy.org/
5. Python Libraries for Data Science
SciPy:
 collection of algorithms for linear algebra, differential equations, numerical
integration, optimization, statistics and more
 part of SciPy Stack
 built on NumPy
5
Link: https://www.scipy.org/scipylib/
6. Python Libraries for Data Science
Pandas:
 adds data structures and tools designed to work with table-like data (similar
to Series and Data Frames in R)
 provides tools for data manipulation: reshaping, merging, sorting, slicing,
aggregation etc.
 allows handling missing data
6
Link: http://pandas.pydata.org/
7. Link: http://scikit-learn.org/
Python Libraries for Data Science
SciKit-Learn:
 provides machine learning algorithms: classification, regression, clustering,
model validation etc.
 built on NumPy, SciPy and matplotlib
7
8. matplotlib:
 python 2D plotting library which produces publication quality figures in a
variety of hardcopy formats
 a set of functionalities similar to those of MATLAB
 line plots, scatter plots, barcharts, histograms, pie charts etc.
 relatively low-level; some effort needed to create advanced visualization
Link: https://matplotlib.org/
Python Libraries for Data Science
8
9. Seaborn:
 based on matplotlib
 provides high level interface for drawing attractive statistical graphics
 Similar (in style) to the popular ggplot2 library in R
Link: https://seaborn.pydata.org/
Python Libraries for Data Science
9
10. Download tutorial notebook
# On the Shared Computing Cluster
[scc1 ~] cp /project/scv/examples/python/data_analysis/dataScience.ipynb .
# On a local computer save the link:
http://rcs.bu.edu/examples/python/data_analysis/dataScience.ipynb
10
12. In [ ]:
Loading Python Libraries
12
#Import Python Libraries
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib as mpl
import seaborn as sns
Press Shift+Enter to execute the jupyter cell
13. In [ ]:
Reading data using pandas
13
#Read csv file
df = pd.read_csv("http://rcs.bu.edu/examples/python/data_analysis/Salaries.csv")
There is a number of pandas commands to read other data formats:
pd.read_excel('myfile.xlsx',sheet_name='Sheet1', index_col=None, na_values=['NA'])
pd.read_stata('myfile.dta')
pd.read_sas('myfile.sas7bdat')
pd.read_hdf('myfile.h5','df')
Note: The above command has many optional arguments to fine-tune the data import process.
15. Hands-on exercises
15
 Try to read the first 10, 20, 50 records;
 Can you guess how to view the last few records; Hint:
16. Data Frame data types
Pandas Type Native Python Type Description
object string The most general dtype. Will be
assigned to your column if column
has mixed types (numbers and
strings).
int64 int Numeric characters. 64 refers to
the memory allocated to hold this
character.
float64 float Numeric characters with decimals.
If a column contains numbers and
NaNs(see below), pandas will
default to float64, in case your
missing value has a decimal.
datetime64, timedelta[ns] N/A (but see the datetime module
in Python’s standard library)
Values meant to hold time data.
Look into these for time series
experiments.
16
17. In [4]:
Data Frame data types
17
#Check a particular column type
df['salary'].dtype
Out[4]: dtype('int64')
In [5]: #Check types for all the columns
df.dtypes
Out[4]: rank
discipline
phd
service
sex
salary
dtype: object
object
object
int64
int64
object
int64
18. Data Frames attributes
18
Python objects have attributes and methods.
df.attribute description
dtypes list the types of the columns
columns list the column names
axes list the row labels and column names
ndim number of dimensions
size number of elements
shape return a tuple representing the dimensionality
values numpy representation of the data
19. Hands-on exercises
19
 Find how many records this data frame has;
 How many elements are there?
 What are the column names?
 What types of columns we have in this data frame?
20. Data Frames methods
20
df.method() description
head( [n] ), tail( [n] ) first/last n rows
describe() generate descriptive statistics (for numeric columns only)
max(), min() return max/min values for all numeric columns
mean(), median() return mean/median values for all numeric columns
std() standard deviation
sample([n]) returns a random sample of the data frame
dropna() drop all the records with missing values
Unlike attributes, python methods have parenthesis.
All attributes and methods can be listed with a dir() function: dir(df)
21. Hands-on exercises
21
 Give the summary for the numeric columns in the dataset
 Calculate standard deviation for all numeric columns;
 What are the mean values of the first 50 records in the dataset? Hint: use
head() method to subset the first 50 records and then calculate the mean
22. Selecting a column in a Data Frame
Method 1: Subset the data frame using column name:
df['sex']
Method 2: Use the column name as an attribute:
df.sex
Note: there is an attribute rank for pandas data frames, so to select a column with a name
"rank" we should use method 1.
22
23. Hands-on exercises
23
 Calculate the basic statistics for the salary column;
 Find how many values in the salary column (use count method);
 Calculate the average salary;
24. Data Frames groupby method
24
Using "group by" method we can:
• Split the data into groups based on some criteria
• Calculate statistics (or apply a function) to each group
• Similar to dplyr() function in R
In [ ]: #Group data using rank
df_rank = df.groupby(['rank'])
In [ ]: #Calculate mean value for each numeric column per each group
df_rank.mean()
25. Data Frames groupby method
25
Once groupby object is create we can calculate various statistics for each group:
In [ ]: #Calculate mean salary for each professor rank:
df.groupby('rank')[['salary']].mean()
Note: If single brackets are used to specify the column (e.g. salary), then the output is Pandas Series object.
When double brackets are used the output is a Data Frame
26. Data Frames groupby method
26
groupby performance notes:
- no grouping/splitting occurs until it's needed. Creating the groupby object
only verifies that you have passed a valid mapping
- by default the group keys are sorted during the groupby operation. You may
want to pass sort=False for potential speedup:
In [ ]: #Calculate mean salary for each professor rank:
df.groupby(['rank'], sort=False)[['salary']].mean()
27. Data Frame: filtering
27
To subset the data we can apply Boolean indexing. This indexing is commonly
known as a filter. For example if we want to subset the rows in which the salary
value is greater than $120K:
In [ ]: #Calculate mean salary for each professor rank:
df_sub = df[ df['salary'] > 120000 ]
In [ ]: #Select only those rows that contain female professors:
df_f = df[ df['sex'] == 'Female' ]
Any Boolean operator can be used to subset the data:
> greater; >= greater or equal;
< less; <= less or equal;
== equal; != not equal;
28. Data Frames: Slicing
28
There are a number of ways to subset the Data Frame:
• one or more columns
• one or more rows
• a subset of rows and columns
Rows and columns can be selected by their position or label
29. Data Frames: Slicing
29
When selecting one column, it is possible to use single set of brackets, but the
resulting object will be a Series (not a DataFrame):
In [ ]: #Select column salary:
df['salary']
When we need to select more than one column and/or make the output to be a
DataFrame, we should use double brackets:
In [ ]: #Select column salary:
df[['rank','salary']]
30. Data Frames: Selecting rows
30
If we need to select a range of rows, we can specify the range using ":"
In [ ]: #Select rows by their position:
df[10:20]
Notice that the first row has a position 0, and the last value in the range is omitted:
So for 0:10 range the first 10 rows are returned with the positions starting with 0
and ending with 9
31. Data Frames: method loc
31
If we need to select a range of rows, using their labels we can use method loc:
In [ ]: #Select rows by their labels:
df_sub.loc[10:20,['rank','sex','salary']]
Out[ ]:
32. Data Frames: method iloc
32
If we need to select a range of rows and/or columns, using their positions we can
use method iloc:
In [ ]: #Select rows by their labels:
df_sub.iloc[10:20,[0, 3, 4, 5]]
Out[ ]:
33. Data Frames: method iloc (summary)
33
df.iloc[0] # First row of a data frame
df.iloc[i] #(i+1)th row
df.iloc[-1] # Last row
df.iloc[:, 0] # First column
df.iloc[:, -1] # Last column
df.iloc[0:7] #First 7 rows
df.iloc[:, 0:2] #First 2 columns
df.iloc[1:3, 0:2] #Second through third rows and first 2 columns
df.iloc[[0,5], [1,3]] #1st and 6th rows and 2nd and 4th columns
34. Data Frames: Sorting
34
We can sort the data by a value in the column. By default the sorting will occur in
ascending order and a new data frame is return.
In [ ]: # Create a new data frame from the original sorted by the column Salary
df_sorted = df.sort_values( by ='service')
df_sorted.head()
Out[ ]:
35. Data Frames: Sorting
35
We can sort the data using 2 or more columns:
In [ ]: df_sorted = df.sort_values( by =['service', 'salary'], ascending = [True, False])
df_sorted.head(10)
Out[ ]:
36. Missing Values
36
Missing values are marked as NaN
In [ ]: # Read a dataset with missing values
flights = pd.read_csv("http://rcs.bu.edu/examples/python/data_analysis/flights.csv")
In [ ]: # Select the rows that have at least one missing value
flights[flights.isnull().any(axis=1)].head()
Out[ ]:
37. Missing Values
37
There are a number of methods to deal with missing values in the data frame:
df.method() description
dropna() Drop missing observations
dropna(how='all') Drop observations where all cells is NA
dropna(axis=1, how='all') Drop column if all the values are missing
dropna(thresh = 5) Drop rows that contain less than 5 non-missing values
fillna(0) Replace missing values with zeros
isnull() returns True if the value is missing
notnull() Returns True for non-missing values
38. Missing Values
38
• When summing the data, missing values will be treated as zero
• If all values are missing, the sum will be equal to NaN
• cumsum() and cumprod() methods ignore missing values but preserve them in
the resulting arrays
• Missing values in GroupBy method are excluded (just like in R)
• Many descriptive statistics methods have skipna option to control if missing
data should be excluded . This value is set to True by default (unlike R)
39. Aggregation Functions in Pandas
39
Aggregation - computing a summary statistic about each group, i.e.
• compute group sums or means
• compute group sizes/counts
Common aggregation functions:
min, max
count, sum, prod
mean, median, mode, mad
std, var
40. Aggregation Functions in Pandas
40
agg() method are useful when multiple statistics are computed per column:
In [ ]: flights[['dep_delay','arr_delay']].agg(['min','mean','max'])
Out[ ]:
41. Basic Descriptive Statistics
41
df.method() description
describe Basic statistics (count, mean, std, min, quantiles, max)
min, max Minimum and maximum values
mean, median, mode Arithmetic average, median and mode
var, std Variance and standard deviation
sem Standard error of mean
skew Sample skewness
kurt kurtosis
42. Graphics to explore the data
42
To show graphs within Python notebook include inline directive:
In [ ]: %matplotlib inline
Seaborn package is built on matplotlib but provides high level
interface for drawing attractive statistical graphics, similar to ggplot2
library in R. It specifically targets statistical data visualization
43. Graphics
43
description
distplot histogram
barplot estimate of central tendency for a numeric variable
violinplot similar to boxplot, also shows the probability density of the
data
jointplot Scatterplot
regplot Regression plot
pairplot Pairplot
boxplot boxplot
swarmplot categorical scatterplot
factorplot General categorical plot
44. Basic statistical Analysis
44
statsmodel and scikit-learn - both have a number of function for statistical analysis
The first one is mostly used for regular analysis using R style formulas, while scikit-learn is
more tailored for Machine Learning.
statsmodels:
• linear regressions
• ANOVA tests
• hypothesis testings
• many more ...
scikit-learn:
• kmeans
• support vector machines
• random forests
• many more ...
See examples in the Tutorial Notebook
45. Conclusion
Thank you for attending the tutorial.
Please fill the evaluation form:
http://scv.bu.edu/survey/tutorial_evaluation.html
Questions:
email: koleinik@bu.edu (Katia Oleinik)
45