Advanced Python CHAPTER 4: Pandas, NumPy and Matplotlib Page 1 Advanced Python Chapter Introduction / Overview Python is widely used in data science because it provides simple syntax and powerful libraries for working with data. Three of the most important libraries for beginners are Pandas, NumPy, and Matplotlib. Pandas is used for tabular data handling, NumPy is used for numerical computation, and Matplotlib is used for data visualization. This chapter introduces students to the practical tools needed for data analysis in Python. It begins with Pandas Series and DataFrames, then explains how to manipulate, clean, combine, and read data from CSV and JSON files. It then introduces NumPy arrays, ndarray objects, indexing, slicing, joining, splitting, searching, sorting, filtering, and random number generation. The chapter also introduces web scraping as a method of collecting data from websites and explains the basic workflow of requesting, parsing, extracting, and storing web data. Finally, the chapter discusses Matplotlib and shows how to create clear visualizations such as line plots, bar charts, histograms, scatter plots, and pie charts. By the end of this chapter, students should be able to load data, clean it, transform it, perform numerical operations, collect basic web data ethically, and visualize results using simple Python programs. Learning Outcomes Upon successful completion of this chapter, students will be able to: 1. Explain the purpose of Pandas, NumPy, and Matplotlib in Python data analysis. 2. Create and use Pandas Series and DataFrame objects for tabular data. 3. Manipulate DataFrames by selecting columns, filtering rows, adding columns, handling missing values, and grouping data. 4. Combine DataFrames using concatenation, merge, and join operations. 5. Read CSV and JSON files using Pandas and perform basic inspection of imported data. 6. Create NumPy arrays and explain the role of ndarray objects in numerical computing. 7. Apply indexing and slicing to access elements, rows, columns, and sub-arrays. 8. Perform NumPy operations such as joining, splitting, searching, sorting, filtering, and generating random numbers. 9. Describe the basic workflow of web scraping and identify ethical precautions before collecting data from websites. 10. Create basic data visualizations using Matplotlib, including line charts, bar charts, histograms, scatter plots, and pie charts. Key Concepts Page 2 Advanced Python Glossary of Key Terms in This Chapter Pandas: A Python library used for data cleaning, analysis, manipulation, and tabular data handling. Series: A one-dimensional labelled array in Pandas, similar to a single column. DataFrame: A two-dimensional labelled data structure in Pandas, similar to a table with rows and columns. CSV: Comma-Separated Values, a common plain-text format used for storing tabular data. JSON: JavaScript Object Notation, a lightweight format used for structured data exchange. NumPy: A Python library used for fast numerical operations and array-based computing. ndarray: The main array object in NumPy that stores homogeneous numerical data efficiently. Indexing: Accessing a single element or row/column by position or label. Slicing: Accessing a range or subset of elements from an array or DataFrame. Web Scraping: The process of extracting data from websites using programs. Matplotlib: A Python library used for creating static, animated, and interactive visualizations. Visualization: The representation of data in graphical form to identify patterns and communicate insights. Table 4.1: Glossary of key terms in Unit 4 4.1 Introduction to Pandas Pandas is a powerful open-source Python library used for data analysis and manipulation. It provides simple data structures and functions for working with structured data such as tables, spreadsheets, CSV files, JSON files, and database outputs. The name Pandas is derived from Panel Data, which refers to multidimensional structured datasets. Pandas is widely used by data analysts, data scientists, researchers, and software developers because it makes data handling easier than using only basic Python lists and dictionaries. Pandas is especially useful when data contains rows and columns, missing values, labels, mixed data types, dates, categories, and numerical values. Figure 4.2: Pandas workflow for tabular data analysis Page 3 Advanced Python Key Insight: Pandas is mainly used when data looks like a table. If the data has rows and columns, a DataFrame is usually the best structure to use. Table 4.2: Important features of Pandas Feature Explanation Example Data loading Reads data from files and data sources. read_csv(), read_json(), read_excel() Data cleaning Handles missing values, duplicate records, and incorrect formats. dropna(), fillna(), drop_duplicates() Data selection Selects rows, columns, and subsets. df["Name"], loc[], iloc[] Data transformation Creates new columns and modifies existing data. df["Total"] = df["A"] + df["B"] Data aggregation Groups and summarizes data. groupby(), mean(), sum() Data export Writes results back to files. to_csv(), to_json() 4.1.1 Installing and Importing Pandas In most data science environments such as Anaconda, Google Colab, and Jupyter Notebook, Pandas is already available. In a local environment, it can be installed using pip. # Install Pandas if it is not already installed pip install pandas # Standard import convention import pandas as pd 4.2 Pandas Series and DataFrames 4.2.1 Pandas Series A Series is a one-dimensional labelled array. It can store integers, floats, strings, or other Python objects. A Series is similar to a single column in a spreadsheet. import pandas as pd marks = pd.Series([78, 85, 92, 66], index=["Amit", "Ravi", "Neha", "Sara"]) print(marks) print(marks["Neha"]) Table 4.3: Components of a Pandas Series Series Component Meaning Values The actual data stored in the Series. Index Labels used to identify each value. Data type The type of values stored, such as int64, float64, or object. 4.2.2 Pandas DataFrame A DataFrame is a two-dimensional labelled data structure with rows and columns. It is the most commonly used data structure in Pandas. DataFrames can be created from dictionaries, lists, CSV files, JSON files, Excel files, databases, or APIs. Page 4 Advanced Python import pandas as pd data = { "Name": ["Amit", "Ravi", "Neha", "Sara"], "Age": [21, 22, 20, 23], "Marks": [78, 85, 92, 66] } df = pd.DataFrame(data) print(df) Table 4.4: Common DataFrame inspection methods DataFrame Operation Purpose Example head() Displays first five rows by default. df.head() tail() Displays last five rows by default. df.tail() shape Shows number of rows and columns. df.shape columns Shows column names. df.columns info() Displays summary of columns and data types. df.info() describe() Displays statistical summary of numerical columns. df.describe() 4.3 Manipulating and Combining DataFrames Data manipulation means changing, cleaning, selecting, filtering, sorting, grouping, or combining data. In real data analysis, raw data is rarely ready for direct use, so DataFrame manipulation is one of the most important skills in Pandas. 4.3.1 Selecting Columns and Rows # Select one column print(df["Name"]) # Select multiple columns print(df[["Name", "Marks"]]) # Select rows using label-based indexing print(df.loc[0]) # Select rows using integer position print(df.iloc[0:2]) Table 4.5: Selecting rows and columns in Pandas Method Used For Example df["col"] Selecting a single column. df["Marks"] df[["col1", "col2"]] Selecting multiple columns. df[["Name", "Age"]] loc[] Selecting by labels or conditions. df.loc[df["Marks"] > 80] iloc[] Selecting by integer position. df.iloc[0:3, 1:3] 4.3.2 Filtering and Creating Columns # Filter students with marks greater than 80 high_scores = df[df["Marks"] > 80] print(high_scores) Page 5 Advanced Python # Create a new column df["Result"] = df["Marks"].apply(lambda x: "Pass" if x >= 40 else "Fail") print(df) 4.3.3 Handling Missing Values Missing values are common in real datasets. Pandas represents missing values using NaN, which means Not a Number. Missing values can be removed, filled, or estimated depending on the situation. import pandas as pd data = {"Name": ["Amit", "Ravi", "Neha"], "Marks": [78, None, 92]} df = pd.DataFrame(data) print(df.isnull()) # Check missing values print(df.dropna()) # Remove rows with missing values print(df.fillna(0)) # Replace missing values with 0 Table 4.6: Data cleaning functions in Pandas Function Purpose isnull() Detects missing values. notnull() Detects non-missing values. dropna() Removes rows or columns with missing values. fillna(value) Replaces missing values with a specified value. drop_duplicates() Removes duplicate rows. 4.3.4 Combining DataFrames Combining DataFrames is required when data is stored in multiple tables. Pandas supports concatenation, merging, and joining. import pandas as pd df1 = pd.DataFrame({"ID": [1, 2], "Name": ["Amit", "Ravi"]}) df2 = pd.DataFrame({"ID": [3, 4], "Name": ["Neha", "Sara"]}) combined = pd.concat([df1, df2], ignore_index=True) print(combined) marks = pd.DataFrame({"ID": [1, 2, 3], "Marks": [78, 85, 92]}) students = pd.DataFrame({"ID": [1, 2, 3], "Name": ["Amit", "Ravi", "Neha"]}) result = pd.merge(students, marks, on="ID") print(result) Table 4.7: DataFrame combining methods Operation Meaning When to Use concat() Stacks DataFrames row-wise or column-wise. When datasets have same columns or same index. merge() Combines DataFrames using a common column. When tables share a key such as ID. join() Combines DataFrames using index. When index labels are meaningful. Page 6 Advanced Python 4.4 Reading CSV and JSON Files Using Pandas Pandas can read data from many file formats. Two of the most common formats are CSV and JSON. CSV files are widely used for tabular data, while JSON is commonly used in web APIs and configuration files. 4.4.1 Reading CSV Files import pandas as pd # Read a CSV file students = pd.read_csv("students.csv") print(students.head()) print(students.shape) print(students.info()) 4.4.2 Writing CSV Files # Save a DataFrame to a CSV file students.to_csv("cleaned_students.csv", index=False) 4.4.3 Reading JSON Files import pandas as pd # Read a JSON file orders = pd.read_json("orders.json") print(orders.head()) Table 4.8: Pandas file reading and writing functions Function Purpose Common Parameter read_csv() Reads a CSV file into a DataFrame. sep, header, names, usecols to_csv() Writes a DataFrame to a CSV file. index=False read_json() Reads a JSON file into a DataFrame. orient to_json() Writes a DataFrame to a JSON file. orient, indent Practical Tip: After reading any file, always use head(), shape, info(), and describe() to understand the structure and quality of the imported data. 4.5 NumPy Arrays and ndarray Objects NumPy stands for Numerical Python. It is a fundamental Python library for scientific computing and numerical operations. NumPy provides the ndarray object, which stores elements of the same data type in a compact and efficient way. Compared with normal Python lists, NumPy arrays are faster, more memory efficient, and support vectorized operations. Vectorization means operations can be performed on entire arrays without writing explicit loops. Page 7 Advanced Python Figure 4.3: NumPy workflow for array-based computation import numpy as np arr = np.array([10, 20, 30, 40]) print(arr) print(type(arr)) print(arr.dtype) Table 4.9: Common NumPy array creation functions Array Creation Function Purpose Example np.array() Creates an array from a list or tuple. np.array([1, 2, 3]) np.zeros() Creates an array filled with zeros. np.zeros(5) np.ones() Creates an array filled with ones. np.ones((2, 3)) np.arange() Creates values in a range. np.arange(1, 10, 2) np.linspace() Creates evenly spaced values. np.linspace(0, 1, 5) np.eye() Creates an identity matrix. np.eye(3) 4.5.1 Attributes of ndarray import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) print(a.shape) # rows and columns print(a.ndim) # number of dimensions print(a.size) # total number of elements print(a.dtype) # data type of elements Table 4.10: Important ndarray attributes Attribute Meaning shape Returns the dimensions of the array. ndim Returns the number of dimensions. Page 8 Advanced Python size Returns the total number of elements. dtype Returns the data type of array elements. itemsize Returns size of each element in bytes. 4.6 Array Indexing and Slicing Indexing is used to access individual elements, while slicing is used to access a range or subset of elements. NumPy indexing starts from 0, just like normal Python lists. import numpy as np a = np.array([10, 20, 30, 40, 50]) print(a[0]) # first element print(a[-1]) # last element print(a[1:4]) # elements from index 1 to 3 print(a[:3]) # first three elements print(a[::2]) # every second element 4.6.1 Indexing 2D Arrays import numpy as np matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(matrix[0, 0]) # row 0, column 0 print(matrix[1, 2]) # row 1, column 2 print(matrix[:, 1]) # all rows, column 1 print(matrix[0:2, 1:3]) # sub-array Table 4.11: NumPy indexing and slicing examples Expression Meaning a[0] First element of a one-dimensional array. a[-1] Last element of a one-dimensional array. a[1:4] Elements from index 1 to 3. matrix[1, 2] Element at row 1 and column 2. matrix[:, 0] All rows from the first column. matrix[0:2, 1:3] Sub-array using row and column ranges. 4.7 Array Operations: Joining and Splitting NumPy arrays support many operations that can be applied to entire arrays. This makes numerical computation simple and efficient. 4.7.1 Vectorized Arithmetic Operations import numpy as np a = np.array([10, 20, 30]) b = np.array([1, 2, 3]) print(a + b) print(a - b) Page 9 Advanced Python print(a * b) print(a / b) print(a ** 2) 4.7.2 Joining Arrays import numpy as np a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) joined = np.concatenate((a, b)) print(joined) # Joining 2D arrays x = np.array([[1, 2], [3, 4]]) y = np.array([[5, 6], [7, 8]]) print(np.vstack((x, y))) # vertical stacking print(np.hstack((x, y))) # horizontal stacking 4.7.3 Splitting Arrays import numpy as np a = np.array([1, 2, 3, 4, 5, 6]) parts = np.array_split(a, 3) print(parts) Table 4.12: NumPy array joining and splitting functions Function Purpose concatenate() Joins arrays along an existing axis. vstack() Stacks arrays vertically. hstack() Stacks arrays horizontally. array_split() Splits an array into multiple parts. reshape() Changes the shape of an array without changing data. 4.8 Searching, Sorting and Filtering Arrays Searching, sorting, and filtering are important for extracting useful information from arrays. NumPy provides efficient functions for these operations. 4.8.1 Searching Arrays import numpy as np a = np.array([10, 20, 30, 20, 40]) result = np.where(a == 20) print(result) Page 10 Advanced Python 4.8.2 Sorting Arrays import numpy as np a = np.array([40, 10, 30, 20]) print(np.sort(a)) 4.8.3 Filtering Arrays import numpy as np a = np.array([10, 25, 30, 45, 50]) filtered = a[a > 30] print(filtered) Table 4.13: Searching, sorting and filtering arrays Operation Example Output Meaning Search np.where(a == 20) Returns indexes where condition is true. Sort np.sort(a) Returns sorted copy of the array. Filter a[a > 30] Returns values greater than 30. Boolean mask a % 2 == 0 Creates True/False condition for each value. Important: Filtering in NumPy is usually done using boolean conditions. The condition creates a True/False mask, and the mask is used to select matching elements. 4.9 Random Number Generation in NumPy Random numbers are used in simulations, sampling, testing, data generation, machine learning, and probability experiments. NumPy provides a random module for generating random values, arrays, and samples. 4.9.1 Random Arrays and Reproducibility A seed is used to produce the same random results again. This is useful for teaching, testing, and experiments where reproducibility is important. import numpy as np np.random.seed(10) print(np.random.randint(1, 100, 5)) Table 4.14: NumPy random number generation functions Function Purpose rand() Generates random floats between 0 and 1. randint() Generates random integers within a range. choice() Selects random values from a list or array. Page 11 import numpy as np print(np.random.randint(1, 10)) # one random integer print(np.random.rand(3)) # 3 random floats from 0 to 1 print(np.random.randint(1, 100, 5)) # 5 random integers Advanced Python shuffle() Randomly changes the order of array elements. normal() Generates random values from a normal distribution. seed() Makes random results reproducible. 4.10 Introduction to Web Scraping Web scraping is the process of extracting data from websites using programs. It is useful when information is available on web pages but not provided as a downloadable dataset or API. A basic web scraping program sends a request to a webpage, receives HTML content, parses the HTML structure, identifies required tags or elements, extracts data, and stores the extracted data in a file or DataFrame. Web scraping should be performed responsibly. Programmers must respect website terms of service, robots.txt rules, copyright, privacy, and server load. Scraping should not be used to collect personal or restricted data without permission. Figure 4.4: Basic web scraping workflow Table 4.15: Steps in a basic web scraping workflow Step Meaning Common Tool Request webpage Download the webpage content. requests Read HTML Receive page source code as text. response.text Parse HTML Understand tags and structure. BeautifulSoup Extract elements Find headings, links, tables, or prices. find(), find_all(), select() Store data Save extracted data for analysis. CSV, JSON, Pandas DataFrame 4.10.1 Simple Web Scraping Example import requests from bs4 import BeautifulSoup Page 12 Advanced Python url = "https://example.com" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") print(soup.title.text) Ethical Reminder: Before scraping a website, check whether the website allows automated access. Prefer official APIs whenever available. 4.11 Introduction to Matplotlib Matplotlib is a Python library used for creating visualizations. It allows programmers to create line graphs, bar charts, histograms, scatter plots, pie charts, and many other types of plots. The most commonly used Matplotlib module is pyplot, which is usually imported as plt. It provides functions that are similar to plotting commands used in MATLAB and other scientific tools. Visualization helps convert numbers into patterns. A good chart can reveal trends, comparisons, distributions, and relationships that may not be clear from a table alone. Figure 4.5: Matplotlib workflow for creating a chart import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [10, 15, 13, 18, 20] plt.plot(x, y) plt.title("Simple Line Plot") plt.xlabel("X Values") plt.ylabel("Y Values") plt.show() Table 4.16: Common Matplotlib pyplot functions Function Purpose plot() Creates a line plot. bar() Creates a bar chart. hist() Creates a histogram. Page 13 Advanced Python scatter() Creates a scatter plot. pie() Creates a pie chart. title() Adds chart title. xlabel(), ylabel() Adds axis labels. legend() Displays chart legend. show() Displays the figure. savefig() Saves chart as an image file. 4.12 Data Visualization Using Matplotlib Different chart types are suitable for different types of questions. A good data analyst chooses a chart based on the purpose of the visualization. Table 4.17: Choosing the correct visualization Chart Type Used For Example Question Line plot Showing trends over time. How did sales change month by month? Bar chart Comparing categories. Which department scored highest? Histogram Showing distribution of numerical values. What is the distribution of exam marks? Scatter plot Showing relationship between two numerical variables. Is study time related to marks? Pie chart Showing parts of a whole. What percentage of students selected each elective? 4.12.1 Bar Chart Example import matplotlib.pyplot as plt subjects = ["Python", "Maths", "DBMS", "OS"] marks = [85, 78, 92, 74] plt.bar(subjects, marks) plt.title("Marks by Subject") plt.xlabel("Subject") plt.ylabel("Marks") plt.show() 4.12.2 Histogram Example import matplotlib.pyplot as plt marks = [45, 56, 67, 78, 89, 90, 72, 63, 55, 81] plt.hist(marks, bins=5) plt.title("Distribution of Marks") plt.xlabel("Marks Range") plt.ylabel("Number of Students") plt.show() 4.12.3 Scatter Plot Example import matplotlib.pyplot as plt Page 14 Advanced Python hours = [1, 2, 3, 4, 5, 6] marks = [40, 50, 55, 65, 75, 85] plt.scatter(hours, marks) plt.title("Study Hours vs Marks") plt.xlabel("Study Hours") plt.ylabel("Marks") plt.show() 4.12.4 Pie Chart Example import matplotlib.pyplot as plt labels = ["Python", "Java", "C++", "R"] students = [40, 25, 20, 15] plt.pie(students, labels=labels, autopct="%1.1f%%") plt.title("Programming Language Preference") plt.show() Visualization Rule: Every chart should have a clear title, axis labels where applicable, readable category names, and a purpose. Avoid adding unnecessary decoration. 4.13 Integrated Practical Example The following example shows how Pandas, NumPy, and Matplotlib can be used together. A small dataset is created, basic analysis is performed, and a visualization is produced. import pandas as pd import numpy as np import matplotlib.pyplot as plt # Create sample data students = pd.DataFrame({ "Name": ["Amit", "Ravi", "Neha", "Sara", "John"], "Python": [78, 85, 92, 66, 74], "Maths": [80, 70, 88, 60, 79] }) # Calculate total and average using Pandas/NumPy students["Total"] = students["Python"] + students["Maths"] students["Average"] = np.round(students["Total"] / 2, 2) print(students) print(students.describe()) # Plot average marks plt.bar(students["Name"], students["Average"]) plt.title("Average Marks of Students") plt.xlabel("Student") plt.ylabel("Average Marks") plt.show() Table 4.18: Role of each library in the integrated example Library Used Role in the Example Pandas Creates and manages the student DataFrame. NumPy Rounds numerical average values. Page 15 Advanced Python Matplotlib Creates a bar chart of average marks. 4.14 Further Reading / Viewing The following resources are recommended for students who want to practice the concepts covered in this chapter. Official Documentation ● Pandas documentation - user guide, API reference, and tutorials. ● NumPy documentation - array operations, random module, and mathematical functions. ● Matplotlib documentation - pyplot tutorial and gallery of chart examples. ● BeautifulSoup documentation - HTML parsing and element extraction. ● Requests documentation - sending HTTP requests in Python. Practice Platforms ● Kaggle Learn - Pandas, Data Visualization, and Python micro-courses. ● W3Schools Python Pandas, NumPy, and Matplotlib tutorials. ● Google Colab notebooks for hands-on Python data analysis. ● Jupyter Notebook practice using small CSV datasets. ● Public sample datasets such as student marks, sales data, weather data, and movie ratings. 4.15 Assessment Questions Part A - Multiple Choice Questions (1 Mark Each) Q1. Which library is mainly used for tabular data analysis in Python? 1. NumPy 2. Pandas 3. Matplotlib 4. Requests Answer: (b) Q2. A Pandas Series is best described as: 1. A two-dimensional table 2. A one-dimensional labelled array 3. A plotting function 4. A web scraping tool Answer: (b) Q3. Which function reads a CSV file into a DataFrame? 1. pd.read_csv() 2. pd.open_csv() 3. np.read_csv() 4. plt.csv() Answer: (a) Q4. What is the main array object in NumPy called? 1. DataFrame 2. Series 3. ndarray Page 16 Advanced Python 4. pyplot Answer: (c) Q5. Which NumPy function is used to sort an array? 1. np.order() 2. np.sort() 3. np.filter() 4. np.arrange() Answer: (b) Q6. Which Matplotlib function is used to display a chart? 1. plt.display() 2. plt.view() 3. plt.show() 4. plt.open() Answer: (c) Q7. Which chart is most suitable for showing trend over time? 1. Pie chart 2. Line plot 3. Histogram 4. Box plot Answer: (b) Q8. Which library is commonly used for parsing HTML in basic web scraping? 1. BeautifulSoup 2. NumPy 3. Matplotlib 4. json Answer: (a) Part B - Short Answer Questions (5 Marks Each) Q9. Define Pandas. Explain any five advantages of using Pandas for data analysis. Q10. Differentiate between Pandas Series and DataFrame with suitable examples. Q11. Explain how to select rows and columns from a DataFrame using loc[] and iloc[]. Q12. Write short notes on handling missing values in Pandas using dropna() and fillna(). Q13. Explain how CSV and JSON files can be read and written using Pandas. Q14. Define NumPy ndarray. Explain shape, ndim, size, and dtype attributes. Q15. Explain indexing and slicing in one-dimensional and two-dimensional NumPy arrays. Q16. Discuss joining and splitting operations in NumPy with examples. Q17. Explain searching, sorting, and filtering arrays in NumPy. Q18. What is web scraping? Explain the basic steps and ethical precautions involved. Q19. Explain the need for data visualization and list common Matplotlib chart types. Page 17 Advanced Python Part C - Long Answer / Essay Questions (10 Marks Each) Q20. Explain the complete Pandas workflow for loading, inspecting, cleaning, transforming, combining, and exporting tabular data. Support your answer with suitable code examples. Q21. Discuss NumPy arrays in detail. Explain array creation, attributes, indexing, slicing, vectorized operations, joining, splitting, searching, sorting, filtering, and random number generation. Q22. Explain data visualization using Matplotlib. Compare line plot, bar chart, histogram, scatter plot, and pie chart with suitable examples and use cases. Q23. Describe a complete mini-project in which a CSV file is loaded using Pandas, numerical operations are performed using NumPy, and results are visualized using Matplotlib. Q24. Web scraping is useful but must be used responsibly. Explain the workflow of web scraping, tools used, possible applications, limitations, and ethical/legal precautions. Part D - Analytical / Case-Based Questions Q25 (Case Study). A college has student performance data stored in a CSV file with columns such as Name, Department, Internal Marks, External Marks, Attendance, and Result. The management wants a Python program to read the data, calculate total marks, find average marks by department, identify students with low attendance, and visualize department-wise performance. 1. Which Pandas functions will be useful for reading and inspecting the data? 2. How can new columns such as Total and Average be created? 3. How can students with attendance below 75% be filtered? 4. Which Matplotlib charts would be suitable for showing department-wise averages and result distribution? 5. Where can NumPy be used in this problem? Q26 (Compare and Analyse). Construct a table comparing Pandas, NumPy, and Matplotlib using at least eight dimensions such as purpose, data structure, common functions, input data type, output type, speed, use case, and example code. After the table, explain how the three libraries work together in a real data analysis project. End of Chapter 4 Page 18