Python Book Chapter 8
Python Book Chapter 8
1. Multi-dimensional Arrays: NumPy's main feature is its `ndarray` (n-dimensional array) object,
which represents a multi-dimensional, homogeneous array of fixed-size items. It allows efficient
storage and manipulation of large datasets. Arrays can be 1-dimensional, 2-dimensional
(matrices), or higher-dimensional.
2. Mathematical Operations: NumPy provides a wide range of mathematical functions that can
be applied element-wise on arrays, such as addition, subtraction, multiplication, division,
exponentiation, trigonometric functions, logarithmic functions, etc. These operations are
optimized for performance and can be performed on entire arrays without the need for explicit
loops.
3. Indexing and Slicing: NumPy offers powerful indexing and slicing capabilities to access
specific elements, rows, columns, or subarrays within an array. It allows for both integer and
boolean indexing, making it easy to extract and manipulate data.
6. Integration with Python Ecosystem: NumPy seamlessly integrates with other popular Python
libraries such as SciPy (Scientific Python), pandas (data manipulation), Matplotlib (data
visualization), and scikit-learn (machine learning). Together, these libraries form a powerful
ecosystem for scientific computing and data analysis in Python.
To use NumPy in your Python code, you need to import the `numpy` module:
import numpy as np
After importing NumPy, you can create arrays, perform mathematical operations, access
elements, and leverage the various features and functionalities offered by NumPy.
Mean ([Link]()):
Reflects the average value of the data.
Susceptible to outliers because it considers all data points equally.
Median ([Link]()):
Represents the middle value of a dataset when arranged in ascending order.
Less affected by outliers compared to the mean.
Useful for datasets with extreme values.
Standard Deviation ([Link]()):
Measures the dispersion or spread of data from its mean.
Provides a sense of how much the values deviate from the mean value.
Indicates the data's variability or consistency.
Q. Write a program to create array and perform operations on arrays like element-wise
arithmetic, slicing, reshaping, etc.
import numpy as np
# Element-wise arithmetic
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
print("Element-wise addition:")
print(a + b)
# Slicing
arr = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("\nSliced array:")
print(arr[:2, 1:])
# Reshaping
arr = [Link](1, 10) # Creates array [1, 2, 3, ..., 9]
reshaped_arr = [Link](3, 3)
print("\nReshaped array:")
print(reshaped_arr)
Element 23 21 55 65 23
Index 0 1 2 3 4
In the above example, we have highlighted the element “55” which is at index “2”.
Indexing Using Index arrays
Indexing can be done in NumPy by using an array as an index.
Numpy arrays can be indexed with other arrays or any other sequence with the exception
of tuples. The last element is indexed by -1 second last by -2 and so on.
import numpy as np
# Create a sequence of integers from 10 to 1 with a step of -2
a = [Link](10, 1, -2)
print("\n A sequential array with a negative step: \n",a)
# Indexes are specified inside the [Link] method.
newarr = a[[Link]([3, 1, 2 ])]
print("\n Elements at these indices are:\n",newarr)
Q. Using boolean indexing on NumPy array to find numbers whose sum row is 10
# You may wish to select those elements whose
# sum of row is a multiple of 10.
import numpy as np
# before transpose
print(gfg, end ='\n\n')
# after transpose
print([Link]())
O/P:
[[1 2 3]
[4 5 6]
[7 8 9]]
[[1 4 7]
[2 5 8]
[3 6 9]]
Parameters:
axes : [None, tuple of ints, or n ints] If anyone wants to pass the parameter then you can but
it’s not all required.
But if you want than remember only pass (0, 1) or (1, 0). Like we have array of shape (2, 3)
to change it (3, 2) you should pass (1, 0) where 1 as 3 and 0 as 2.
Returns: ndarray
# after transpose
print([Link](1, 0))
O/P:
[[1 2]
[4 5]
[7 8]]
[[1 4 7]
[2 5 8]]
This is just a brief introduction to NumPy. NumPy offers many more advanced features, such as
advanced indexing, reshaping, sorting, and statistical functions. You can refer to the official
NumPy documentation ([Link] for detailed information and examples on using
NumPy for various scientific computing tasks.
First, you need to install NumPy if you haven't already. You can do this by running the following
command in your Python environment:
pip install numpy
Once NumPy is installed, you can import it in your Python script to use its array functionality:
import numpy as np
Now, let's see how to create arrays, perform operations with scalars, and manipulate array
elements:
1. Creating arrays:
- Creating an array from a list:
arr1 = [Link]([1, 2, 3, 4, 5])
print(arr1) # Output: [1 2 3 4 5]
- Scalar multiplication:
arr4 = [Link]([1, 2, 3])
scalar = 2
result = arr4 * scalar
print(result) # Output: [2 4 6]
Creating Scalars:
Scalars in NumPy are represented using basic Python types like int or float.
import numpy as np
scalar_int = np.int32(5)
scalar_float = np.float64(3.14)
These examples demonstrate basic operations with arrays and scalars using the NumPy library in
Python. Remember to adapt the syntax according to the programming language you are using, as
array functionality and syntax may differ.
8.3 Universal Array Function
Universal functions (ufuncs) in NumPy are functions that operate element-wise on arrays,
applying the same operation to each element of the array. They are designed to efficiently handle
large arrays without the need for explicit loops. Here are some commonly used universal array
functions in NumPy:
1. `[Link](x)` - Compute the absolute value of each element in the array `x`.
2. `[Link](x)` - Compute the square root of each element in the array `x`.
3. `[Link](x)` - Compute the exponential (e^x) of each element in the array `x`.
4. `[Link](x)` - Compute the natural logarithm of each element in the array `x`.
5. `[Link](x)`, `[Link](x)`, `[Link](x)` - Compute the sine, cosine, and tangent of each element in
the array `x`, respectively. Similarly, there are trigonometric functions like `[Link]()`,
`[Link]()`, and `[Link]()` to compute inverse trigonometric values.
7. `[Link](x, y)`, `[Link](x, y)`, `[Link](x, y)`, `[Link](x, y)` - Perform element-
wise addition, subtraction, multiplication, and division between arrays `x` and `y`.
8. `[Link](x, y)` - Compute the exponentiation of each element in array `x` with the
corresponding element in array `y`.
9. `[Link](x)`, `[Link](x)`, `[Link](x)` - Compute the floor, ceiling, and rounding of each
element in the array `x`.
These are just a few examples of universal array functions in NumPy. There are many more
functions available to perform various mathematical operations on arrays efficiently. You can
explore the official NumPy documentation for a comprehensive list of available ufuncs and their
usage.
1. Saving Arrays:
To save an array to a file, you can use the `[Link]()` or `[Link]()` function. Here's how you
can use them:
- `[Link](file, arr)` - Saves a single array to a binary file with the `.npy` extension.
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
[Link]('[Link]', arr)
- `[Link](file, arr1, arr2, ...)` - Saves multiple arrays into a single compressed `.npz` file.
import numpy as np
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
[Link]('[Link]', arr1=arr1, arr2=arr2)
2. Loading Arrays:
To load arrays from files, you can use the `[Link]()` or `[Link]()` function. Here's how to use
them:
- `[Link](file)` - Loads multiple arrays from a `.npz` file. The returned object works as a
dictionary-like structure.
import numpy as np
data = [Link]('[Link]')
arr1 = data['arr1']
arr2 = data['arr2']
print(arr1) # Output: [1 2 3]
print(arr2) # Output: [4 5 6]
The saved arrays can be loaded into the program at a later time using these functions. It's
important to note that the file extensions `.npy` and `.npz` are used to differentiate between
single and multiple array files.
Additionally, NumPy provides other I/O functions such as `[Link]()` and `[Link]()` for
saving and loading arrays in plain text format, `[Link]()` for loading arrays from
delimited text files, and more. These functions offer various options for customizing the output
format and loading data with specific configurations.
Remember to import the NumPy library (`import numpy as np`) before using these functions.
Pandas is an open-source Python library that provides powerful data manipulation and analysis
tools. It is built on top of NumPy and is widely used in data science, data analysis, and machine
learning applications. Pandas introduces two key data structures: Series and DataFrame.
1. Series:
A Series is a one-dimensional labeled array that can hold any data type. It is similar to a
column in a spreadsheet or a single column of a database table. The Series object consists of two
main components: the data (values) and the index (labels). The index provides a label for each
element in the Series, allowing for easy and efficient data access and alignment.
2. DataFrame:
A DataFrame is a two-dimensional labeled data structure, resembling a table or a spreadsheet.
It consists of rows and columns, where each column can hold different types of data. DataFrames
are highly versatile and provide powerful functionalities for data manipulation, cleaning,
reshaping, grouping, merging, and more. They allow for efficient handling of structured data and
are commonly used for data analysis and preprocessing tasks.
Pandas provides a wide range of functions and methods to perform various operations on Series
and DataFrame objects. Some of the key features and use cases of Pandas include:
- Data cleaning and preprocessing: Pandas offers functions to handle missing values, duplicate
data, and outliers, as well as tools for data transformation, normalization, and feature
engineering.
- Data exploration and analysis: Pandas provides efficient methods for descriptive statistics,
aggregations, filtering, sorting, and visualizations. It allows you to gain insights into the data,
identify patterns, and extract meaningful information.
- Data integration and merging: Pandas enables combining multiple datasets based on common
columns or indices, performing joins, concatenation, and merging operations.
- Time series analysis: Pandas has extensive support for working with time series data, including
date/time indexing, resampling, shifting, and rolling window calculations.
- Input and output: Pandas can read and write data in various file formats, including CSV, Excel,
SQL databases, and more. It simplifies the process of loading and saving data from different
sources.
Pandas is widely used in industries such as finance, healthcare, marketing, social sciences, and
more. It provides a high-level, intuitive interface for data manipulation and analysis, making it a
popular choice among data scientists, analysts, and researchers. Its integration with other
libraries like NumPy, Matplotlib, and scikit-learn further enhances its capabilities in data
analysis workflows.
In this example, a Series object `s` is created from a Python list `data`. The default index is
assigned, starting from 0, and the values from the list are stored in the Series.
Pandas DataFrames, on the other hand, are two-dimensional labeled data structures resembling
tables or spreadsheets. A DataFrame consists of rows and columns, where each column can hold
different types of data. It provides a tabular structure with additional functionalities for data
manipulation, analysis, and integration.
In this example, a DataFrame `df` is created from a dictionary `data`. The keys of the dictionary
represent column names, and the values are the corresponding data. The DataFrame is structured
with rows and columns, and each column holds a different type of data.
Index objects in pandas are immutable arrays that hold the axis labels (row labels or column
labels) for Series and DataFrames. Index objects provide several functionalities for data
alignment, selection, and reindexing.
Reindexing is the process of creating a new object with a different index. It allows you to change
the row or column labels of a Series or DataFrame, aligning the data with the new index labels.
The `reindex()` method in pandas facilitates this operation.
In this example, the original DataFrame `df` is reindexed with the labels `['A', 'B', 'C']`. The
`reindex()` method creates a new DataFrame `df_reindexed` with the specified index labels, and
the data is aligned accordingly.
Reindexing allows you to handle missing values, align data with different datasets, or change the
order of the rows/columns in a DataFrame.
In pandas, you can drop entries (rows or columns) from a DataFrame using the `drop()` method.
To select specific entries from a DataFrame, you can use indexing and slicing techniques.
1. Dropping Entries:
To drop entries from a DataFrame, you can use the `drop()` method and specify the labels of
the rows or columns you want to remove. By default, `drop()` removes rows, but you can also
drop columns by specifying the `axis` parameter.
# Creating a DataFrame
data = {'Name': ['John', 'Emma', 'Michael'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']}
df = [Link](data)
Output:
Name Age City
0 John 25 New York
2 Michael 35 Paris
In this example, the row with index 1 is dropped using the `drop()` method. The resulting
DataFrame `df_dropped` no longer contains the dropped row.
If you want to drop columns, you need to specify the `axis` parameter as 1:
df_dropped = [Link](['Age', 'City'], axis=1) # Drop columns 'Age' and 'City'
2. Selecting Entries:
To select specific entries (rows and columns) from a DataFrame, you can use indexing and
slicing techniques.
- Selecting rows by index label or index position:
# Selecting rows by index label
row = [Link][1] # Get the row with index label 1
These are just a few examples of selecting entries from a DataFrame. Pandas provides various
indexing and slicing techniques to select specific rows, columns, or individual entries based on
labels or positions.
Keep in mind that indexing in pandas starts from 0, and you can also use boolean indexing and
other advanced selection methods for more complex selection operations.
8.8 Data Alignment, Rank and Sort
Data alignment, ranking, and sorting are important operations in pandas that allow you to align
data, assign ranks to values, and sort the data based on specific criteria. Let's go through each of
these operations:
1. Data Alignment:
Data alignment in pandas refers to the process of aligning data based on index labels. When
performing operations on multiple Series or DataFrames, pandas automatically aligns the data
based on their index labels, ensuring that corresponding elements are matched together.
2. Rank:
The rank method in pandas assigns ranks to values within a Series or DataFrame based on their
numerical order. The `rank()` function is used to perform this operation.
import pandas as pd
# Creating a Series
s = [Link]([3, 1, 2, 4, 5])
In this example, the `rank()` function assigns ranks to the values in the Series `s`. The smallest
value (1) receives the lowest rank, while the largest value (5) receives the highest rank.
3. Sorting:
Sorting in pandas allows you to sort the data in a Series or DataFrame based on specific
criteria, such as index labels or column values. The `sort_values()` and `sort_index()` functions
are commonly used for sorting.
import pandas as pd
# Creating a Series
s = [Link]([3, 1, 2, 4, 5])
# Sorting by values
sorted_values = s.sort_values()
print(sorted_values)
# Sorting by index
sorted_index = s.sort_index()
print(sorted_index)
Output:
1 1
2 2
0 3
3 4
4 5
dtype: int64
0 3
1 1
2 2
3 4
4 5
In this example, `sort_values()` sorts the Series `s` based on its values in ascending order,
while `sort_index()` sorts the Series based on its index labels in ascending order.
For DataFrames, you can specify the axis parameter (`axis=0` for rows, `axis=1` for columns) to
control the sorting direction.
These operations are fundamental in data manipulation and analysis using pandas. They help in
aligning data, assigning ranks, and sorting the data to extract meaningful insights and perform
further computations.
8.9 Summary Statics, Missing Data, Index Hierarchy
Summary Statistics, Missing Data, and Index Hierarchy are important concepts in pandas for
data analysis and manipulation. Let's explore each of these concepts:
1. Summary Statistics:
Pandas provides several functions to compute summary statistics for numerical data in a
DataFrame or Series. These functions allow you to gain insights into the data distribution, central
tendency, dispersion, and other statistical measures.
# Creating a DataFrame
data = {'Name': ['John', 'Emma', 'Michael'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 70000]}
df = [Link](data)
Age Salary
count 3.000000 3.000000
mean 30.000000 60000.000000
std 5.000000 10000.000000
min 25.000000 50000.000000
25% 27.500000 55000.000000
50% 30.000000 60000.000000
75% 32.500000 65000.000000
max 35.000000 70000.000000
In this example, summary statistics such as mean and descriptive statistics are computed for the
numerical columns 'Age' and 'Salary' in the DataFrame `df`.
2. Missing Data:
Missing data refers to the presence of null or NaN (Not a Number) values in a DataFrame or
Series. Pandas provides functions to handle missing data, including identifying missing values,
removing or filling missing values, and handling missing data in computations.
A B C
0 1.0 5.0 9.0
A B C
0 1.0 5.0 9.0
1 0.0 6.0 10.0
2 3.0 0.0 11.0
3 4.0 8.0 0.0
In this example, missing values are identified using `isnull()`. Rows with missing values are
removed using `dropna()`. Missing values are filled with 0 using `fillna()`.
3. Index Hierarchy:
Index hierarchy, also known as MultiIndex, allows you to have multiple levels of index in a
DataFrame. It provides a way to represent higher-dimensional data in a tabular structure. With
index hierarchy, you can perform advanced data selection, grouping, and analysis.
In this example, a DataFrame `df` is created with two levels of index hierarchy: 'Category' and
'Subcategory'. The `MultiIndex` object is created from the columns 'Category' and 'Subcategory',
and the DataFrame is set with this multi-index using `set_index()`. The columns 'Category' and
'Subcategory' are dropped using `drop()` to achieve the desired index hierarchy.
Index hierarchy allows for more advanced data manipulation, slicing, and analysis by
leveraging multiple levels of indexing.
These concepts in pandas provide powerful tools to perform data analysis, handle missing data,
compute summary statistics, and work with multi-level index structures. They are essential for
data cleaning, exploratory data analysis, and extracting insights from structured datasets.
1. Importing Matplotlib:
Before using Matplotlib, you need to import it. Typically, Matplotlib is imported under
the alias `plt`.
import [Link] as plt
[Link](x, y)
[Link]()
This will display a simple line plot with the x-axis values `[1, 2, 3, 4, 5]` and the y-axis values
`[2, 4, 6, 8, 10]`.
In this example, the line style is set to a dashed line (`linestyle='--'`), the marker style is set to a
circle (`marker='o'`), and the color is set to red (`color='r'`). The x-axis label, y-axis label, and
plot title are added using `xlabel()`, `ylabel()`, and `title()` functions, respectively. The `grid()`
function adds a grid to the plot.
# Scatter plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y)
[Link]()
# Bar plot
x = ['A', 'B', 'C', 'D']
y = [3, 7, 2, 5]
[Link](x, y)
[Link]()
# Histogram
data = [1, 2, 3, 3, 4, 5, 5, 5, 6, 7]
[Link](data, bins=5)
[Link]()
# Pie chart
sizes = [15, 30, 45, 10]
labels = ['A', 'B', 'C', 'D']
[Link](sizes, labels=labels, autopct='%1.1f%%')
[Link]()
These examples demonstrate how to create scatter plots, bar plots, histograms, and pie charts
using Matplotlib. Each plot type has its own set of customization options.
Matplotlib offers extensive flexibility and control over plot customization, allowing you to create
visually appealing and informative plots. You can refer to the Matplotlib documentation and
examples for more in-depth guidance on specific plot types, customization options, and advanced
plotting techniques.
Solved Programs
Q.1 Create 5×5 2D numpy assay and retrieve top left corner 2×2 array fromit.[2marks]
Ans:
import numpy as np
x = [Link]((5,5),7)
print("Original Array:")
print(x)
print(x[0:2,1:3])
Q.2 Create pandas dataframe using two dimensional list. Perform following operations.
Count number of [Link] missing values in first column. Display number of columns in data
frame.
Ans:
import pandas as pd# List1
lst = [['tom', 'reacher', 25], ['krish', 'pete', 30],
['nick', 'wilson', 26], ['juli', 'williams', 22]]
Q.3 Create a series from numpy array and find max and mean of unique itemsof series.
import pandas as pd
Excercizes
Q.1 Write a Python program to create a time series plot using Pandas and Matplotlib.
Q.2 Write a Python program to create multiple subplots using Pandas and Matplotlib.
Q.3 Write a Python program to customize various aspects of a plot such as colors, labels, titles,
legends, etc., using Pandas and Matplotlib
Q.4 Write a Python program to save a plot as an image file (e.g., PNG, JPEG) using Pandas and
Matplotlib.
Q.5 Write a Python program to create an interactive plot using Pandas, Matplotlib, and an
interactive backend like Plotly or Bokeh.