Saturday, 9 March 2024

Skip Lists: A Probabilistic Approach to Ordered Data

SkipList is a specialized form of a Linked List optimized for rapid search and insertion operations.

 

In SkipLists, both insertion and search tasks are accomplished with a time complexity of O(log n), where 'n' represents the number of elements contained within the SkipList.

 

What are the steps involved in constructing a SkipList?

Let's consider a scenario where we have a linked list containing elements arranged in ascending order.

 


 

In SkipLists, even though elements are sorted, traditional binary search isn't applicable because the middle element's address isn't known.

 

Sentinel Node

Within SkipLists, a sentinel node serves as a special marker at either the beginning or end of the list. These nodes offer a consistent starting point for traversing the SkipList, irrespective of its size or the number of levels it encompasses. They simplify the implementation of operations like searching, insertion, and deletion by ensuring that nodes containing actual data always have predecessors and successors.

 

By incorporating a sentinel node with predictable values (typically positive or negative infinity), the need for handling special cases in the code is alleviated when dealing with scenarios such as locating the first or last element, or inserting at the list's extremities.

 

The presence of a sentinel node guarantees consistent behavior regardless of whether the list is empty or populated. Consequently, code interacting with the SkipList can uniformly treat the sentinel node as a reference point for traversals or comparisons.

 


 

The skips in SkipLists are determined as follows:

In SkipLists, the addition of a layer above the base layer, often referred to as L0, introduces skips in the structure. While L0 is a conventional linked list where all nodes are connected sequentially, L1 incorporates skips.

 

Upon insertion of a new element into the skip list, it initially resides on the lowest level with just one level. However, as the skip list expands, certain nodes may be elevated to higher levels with a certain probability. This promotion process is typically stochastic, with nodes ascending to higher levels based on a predefined probability distribution. 


For instance, a random number generator might be employed to determine whether a node should be elevated to a higher level. If the generated random number falls within a specific range or satisfies particular conditions, the node is promoted to the next level. This process continues until a level is reached where further promotion is not possible. Through this random promotion mechanism, SkipLists achieve a balanced distribution of nodes across various levels, facilitating efficient search, insertion, and deletion operations.

 

In simpler terms, as the skip list expands, nodes have a chance to "skip" to higher levels with a certain probability, thus enhancing the overall structure's balance and operational efficiency.

 

For example, let's say we're generating random numbers within the range of 1 to 10. If a generated number is less than 3, the corresponding node is promoted to the next level; otherwise, it remains at its current level.

 

Suppose nodes containing elements 5, 20, 31, and 65 are promoted to the next level based on the aforementioned random number selection logic. The skip list will appear as follows after the addition of the new level, L1.

 


 

At each level of the SkipList, there exists a linked list comprised of nodes representing elements in the list. Each node holds data and pointers to subsequent node(s) within the same level, enabling horizontal traversal within that level. Moreover, each node might possess pointers to nodes in the level(s) beneath it, constructing a staircase-like structure within the SkipList. This hierarchical arrangement facilitates efficient navigation and search operations across multiple levels, contributing to the skip list's overall performance. 


Construction of L2 level linked list

To construct the L2 level linked list on top of the L1 level linked list, we iterate through the elements of the L1 linked list one by one. For each element, we apply the same random number logic as we did during the construction of the L1 level linked list.

 

Let's assume that the nodes containing elements 20 and 65 are promoted to the next level based on the random number selection logic. After adding the new level L2, the skip list will resemble the following structure.

 


Now the skip list has 3 layers.

 

How can I decide number of levels in skip list?

Determining the number of levels in a skip list involves a randomized process during insertion rather than a direct decision. Here's a general approach to guide the determination of skip list levels:

 

Set a maximum level: Establish the maximum number of levels desired for the skip list. This maximum level serves as an upper limit on the skip list's height.

 

Randomly assign levels: When inserting a new node, employ a random process to determine the number of levels for that node. Typically, this involves generating a random number to determine the node's level.

 

Limit level assignment: Ensure that the assigned number of levels for each node does not surpass the maximum level set in step 1. If the random process yields a level count exceeding the maximum level, cap the node's level at the maximum.

 

Adjust the maximum level: Monitor the skip list's growth and the number of nodes over time. Periodically evaluate the skip list's height and adjust the maximum level as necessary to maintain a balanced structure and optimize performance.

 

By implementing a maximum level and employing a randomized process for level assignment during insertion, you can manage the skip list's height effectively while still facilitating efficient operations such as search, insertion, and deletion.


How to perform search in a Skip List?

In SkipLists, the search operation initiates from the topmost level, commencing at the sentinel node of that level. Here's how the search for an element, let's say 33, is conducted:

 

Start at the top level: Begin the search from the highest level of the skip list, commencing at the sentinel node. The sentinel node serves as the entry point into the skip list.


 


Move horizontally: Traverse horizontally across the current level of the skip list, progressing from one node to another based on the value being searched for. Compare the search value with the values stored in the nodes at the current level.

If the search value is greater than the value of the current node but less than the value of the next node, proceed downwards to the next level of the skip list and continue the horizontal search at that level. Repeat this process until reaching the bottom level of the skip list.

By following this procedure, it becomes evident that the element 33 lies between the nodes containing values 20 and 65 at Level 2. 




By applying the same steps in L1, we can identify the element 33 is in between 31 and 65 of L1 elements.

 


Finally we can find the element 33 at level L0.

 


Once you reach the bottom level of the skip list, continue searching horizontally until finding the target value or reaching the end of the skip list. If the target value is found, return the node containing the value. If the target value is not found, return a "not found" indication.

 

How to perform Insertion?

Let’s insert the key 11.

 

To insert an element 11, first we need to find the position for the new key 11. It can be determined by search operation that we discussed above. From the search operation, we can identify the element 11 is inserted between the nodes 9 and 13.

 

 


Once the insertion position in the lowest level (level 0) is determined, a random process is simulated to decide the number of levels the new element will occupy in the skip list. Subsequently, a new node with the desired value is created and inserted into the appropriate position at each level of the skip list. Pointers are adjusted to connect the new node both horizontally and vertically within the skip list.

 

Assuming for the element 11, the random level generation process determines that it will occupy 3 levels, the final skip list will appear as follows:

 

 


When to use SkipList?

Skip lists are an excellent choice in various scenarios requiring efficient search, insertion, and deletion operations, particularly for large and dynamic datasets. Here are some situations where skip lists are particularly advantageous:

 

Balanced performance: Skip lists offer an average-case time complexity of O(log n) for search, insertion, and deletion operations, making them efficient for datasets of various sizes.

 

Dynamic datasets: Skip lists dynamically adjust their structure as elements are added or removed, making them ideal for scenarios with frequent dataset modifications.

 

Ordered traversal: Skip lists maintain elements in sorted order, enabling efficient ordered traversal, which is beneficial for processing data sequentially without the need for sorting.

 

Concurrency: Concurrent skip lists support multiple threads concurrently accessing and modifying the structure, providing efficient concurrent operations without requiring explicit synchronization.

 

No strict balancing required: Skip lists achieve balance through probabilistic methods, eliminating the need for strict balancing mechanisms found in other data structures like AVL trees or red-black trees, leading to simpler implementation and maintenance.

 

Memory efficiency: Skip lists typically require less memory overhead compared to other balanced data structures, especially when additional balance information is not necessary.

 

In summary, skip lists are versatile data structures suitable for a wide range of applications, including databases, indexing, caching, and concurrent data structures, where efficient operations on dynamic datasets are essential.


Sample implementation of SkipList.

 

SkipListNode.java

package com.sample.app.ds;

import java.util.ArrayList;
import java.util.List;

/**
 * Represents a node in a SkipList data structure.
 *
 * @param <E> The type of value stored in the node.
 */
public class SkipListNode<E> {
	private E value;
	public List<SkipListNode<E>> nextNodes;

	/**
	 * Constructs a SkipListNode with the specified value.
	 *
	 * @param value The value to be stored in the node.
	 */
	public SkipListNode(E value) {
		this.value = value;
		nextNodes = new ArrayList<>();
	}

	/**
	 * Retrieves the value stored in the node.
	 *
	 * @return The value stored in the node.
	 */
	public E getValue() {
		return value;
	}

	/**
	 * Retrieves the level of the node in the SkipList. The level is determined by
	 * the number of nextNodes.
	 *
	 * @return The level of the node.
	 */
	public int level() {
		return nextNodes.size() - 1;
	}

	/**
	 * Returns a string representation of the SkipListNode.
	 *
	 * @return A string representation of the SkipListNode.
	 */
	@Override
	public String toString() {
		return "" + value;
	}
}

SkipListIterator.java

package com.sample.app.ds;

import java.util.Iterator;

/**
 * Iterator for traversing through elements of a SkipList.
 *
 * @param <E> The type of elements stored in the SkipList.
 */
public class SkipListIterator<E extends Comparable<E>> implements Iterator<E> {
	private SkipList<E> list;
	private SkipListNode<E> current;

	/**
	 * Constructs a SkipListIterator for the given SkipList.
	 *
	 * @param list The SkipList to be iterated over.
	 */
	public SkipListIterator(SkipList<E> list) {
		this.list = list;
		this.current = list.getHead();
	}

	/**
	 * Checks if there is a next element in the SkipList.
	 *
	 * @return true if there is a next element, otherwise false.
	 */
	@Override
	public boolean hasNext() {
		return current.nextNodes.get(0) != null;
	}

	/**
	 * Retrieves the next element from the SkipList.
	 *
	 * @return The next element in the iteration.
	 */
	@Override
	public E next() {
		current = current.nextNodes.get(0);
		return current.getValue();
	}

	/**
	 * Unsupported operation. This method throws UnsupportedOperationException.
	 *
	 * @throws UnsupportedOperationException if remove operation is not supported.
	 */
	@Override
	public void remove() throws UnsupportedOperationException {
		throw new UnsupportedOperationException();
	}
}

SkipList.java

package com.sample.app.ds;

import java.util.Iterator;

/**
 * Represents a SkipList data structure.
 *
 * @param <E> The type of elements stored in the SkipList, must be comparable.
 */
public class SkipList<E extends Comparable<E>> {
	private SkipListNode<E> head;
	private int maxLevel;
	private int size;

	private static final double PROBABILITY_TO_DECIDE_LEVEL = 0.5;

	private SkipListNode<E> find(E e) {
		return find(e, head, maxLevel);
	}

	private SkipListNode<E> find(E e, SkipListNode<E> current, int level) {
		do {
			current = findNext(e, current, level);
		} while (level-- > 0);
		return current;
	}

	private SkipListNode<E> findNext(E e, SkipListNode<E> current, int level) {
		SkipListNode<E> next = current.nextNodes.get(level);
		while (next != null) {
			E value = next.getValue();
			if (lessThan(e, value))
				break;
			current = next;
			next = current.nextNodes.get(level);
		}
		return current;
	}

	private boolean lessThan(E a, E b) {
		return a.compareTo(b) < 0;
	}

	private boolean equalTo(E a, E b) {
		return a.compareTo(b) == 0;
	}

	/**
	 * Constructs an empty SkipList.
	 */
	public SkipList() {
		size = 0;
		maxLevel = 0;
		head = new SkipListNode<>(null);
		head.nextNodes.add(null);
	}

	/**
	 * Returns the head of the SkipList.
	 *
	 * @return The head node of the SkipList.
	 */
	public SkipListNode<E> getHead() {
		return head;
	}

	/**
	 * Adds an element to the SkipList.
	 *
	 * @param e The element to be added.
	 * @return true if the element was added successfully, false if it already
	 *         exists in the SkipList.
	 */
	public boolean add(E e) {
		if (contains(e))
			return false;

		size++;

		// Decide maximum levels to this element
		int level = 0;
		while (Math.random() < PROBABILITY_TO_DECIDE_LEVEL)
			level++;

		while (level > maxLevel) {
			head.nextNodes.add(null);
			maxLevel++;
		}

		SkipListNode<E> newNode = new SkipListNode<>(e);
		SkipListNode<E> current = head;
		do {
			current = findNext(e, current, level);
			newNode.nextNodes.add(0, current.nextNodes.get(level));
			current.nextNodes.set(level, newNode);
		} while (level-- > 0);

		return true;
	}

	/**
	 * Returns the size of the SkipList.
	 *
	 * @return The number of elements in the SkipList.
	 */
	public int size() {
		return size;
	}

	/**
	 * Checks if the SkipList contains the specified element.
	 *
	 * @param o The element to be checked for containment.
	 * @return true if the SkipList contains the element, otherwise false.
	 */
	public boolean contains(Object o) {
		if (o == null)
			return false;
		@SuppressWarnings("unchecked")
		E e = (E) o;
		SkipListNode<E> node = find(e);
		return node != null && node.getValue() != null && equalTo(node.getValue(), e);
	}

	/**
	 * Deletes an element from the SkipList.
	 *
	 * @param e The element to be deleted.
	 * @return true if the element was deleted successfully, false if it does not
	 *         exist in the SkipList.
	 */
	public boolean delete(E e) {
		if (!contains(e))
			return false;

		SkipListNode<E> current = head;
		for (int i = maxLevel; i >= 0; i--) {
			while (current.nextNodes.get(i) != null && lessThan(current.nextNodes.get(i).getValue(), e))
				current = current.nextNodes.get(i);

			if (current.nextNodes.get(i) != null && equalTo(current.nextNodes.get(i).getValue(), e))
				current.nextNodes.set(i, current.nextNodes.get(i).nextNodes.get(i));
		}
		size--;
		return true;
	}

	/**
	 * Returns an iterator over the elements in the SkipList.
	 *
	 * @return An iterator over the elements in the SkipList.
	 */
	public Iterator<E> iterator() {
		return new SkipListIterator<>(this);
	}

	/**
	 * Returns a string representation of the SkipList.
	 *
	 * @return A string representation of the SkipList.
	 */
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("SkipList [head=").append(head).append(", maxLevel=").append(maxLevel).append(", size=")
				.append(size).append("]").append("\n");

		Iterator<E> iterator = this.iterator();

		while (iterator.hasNext()) {
			builder.append(iterator.next()).append("->");
		}
		String result = builder.toString();

		return result.substring(0, result.length() - 2);
	}
}

SkipListDemo.java

package com.sample.app;

import com.sample.app.ds.SkipList;

public class SkipListDemo {
	public static void main(String[] args) {
		SkipList<Integer> skipList = new SkipList<>();
		System.out.println(skipList + "\n");

		// Add elements to the skip list

		skipList.add(5);
		skipList.add(65);
		skipList.add(9);
		skipList.add(33);
		skipList.add(13);
		skipList.add(31);
		skipList.add(27);
		skipList.add(71);
		skipList.add(3);
		skipList.add(20);

		System.out.println(skipList + "\n");

		System.out.println("Delete 31 and 3 from the skip list");
		skipList.delete(31);
		skipList.delete(3);
		System.out.println(skipList + "\n");
	}
}

Output

SkipList [head=null, maxLevel=0, size=0

SkipList [head=null, maxLevel=5, size=10]
3->5->9->13->20->27->31->33->65->71

Delete 31 and 3 from the skip list
SkipList [head=null, maxLevel=5, size=8]
5->9->13->20->27->33->65->71


                                                  System Design Questions

In-memory vs Disk based Database Management systems

 

Database systems are classified into two main categories: in-memory and disk-based, based on how they store and manage data.

 

In-memory databases

In-memory database management systems primarily store data in memory and utilize disk for recovery and logging purposes.

 

Examples

H2 Database: H2 is a Java-based open-source relational database management system. It supports both in-memory databases and persistent disk-based databases. H2 offers features such as ACID transactions, SQL support, and compatibility with other database systems. It finds applications in embedded systems, testing environments, and small to medium-sized applications.

 

Apache Derby: Apache Derby is an open-source relational database management system implemented in Java. It supports both in-memory databases and persistent disk-based databases. Derby is fully transactional and supports SQL queries, stored procedures, and triggers. It is commonly used in embedded systems, desktop applications, and small-scale web applications.

 

SAP HANA: SAP HANA is a high-performance in-memory database designed for processing and analyzing data stored in memory instead of traditional disk-based storage. This enables faster data processing and real-time analytics, making it suitable for applications requiring rapid access to large volumes of data, such as enterprise resource planning (ERP), customer relationship management (CRM), and business intelligence (BI) systems.

 

Apache Geode: Apache Geode is an open-source distributed in-memory data management platform offering low-latency, high-throughput data access and processing. It is commonly used for real-time analytics, event processing, and caching in large-scale distributed systems.

 

MemSQL: MemSQL is a high-performance relational in-memory database well-suited for large-scale data analytics and transactional workloads.

 

 

Disk based databases

Disk-based DBMS primarily store most of their data on disk and utilize memory for caching disk contents or as temporary storage.

 

Examples of disk-based database management systems (DBMS) include:

 

MySQL: MySQL is a widely-used open-source relational database management system for web applications and other software. It stores data on disk and offers features such as ACID transactions, SQL support, and scalability.

 

PostgreSQL: PostgreSQL is an open-source object-relational database management system known for its advanced features and reliability. It stores data on disk and supports ACID transactions, SQL queries, stored procedures, and various data types.

 

Oracle Database: Oracle Database is a proprietary relational database management system developed by Oracle Corporation. It stores data on disk and offers features such as high availability, scalability, and advanced security options.

 

Microsoft SQL Server: Microsoft SQL Server is a relational database management system developed by Microsoft. It stores data on disk and provides features such as ACID transactions, SQL support, and integration with other Microsoft products.

 

MongoDB: MongoDB is a document-oriented NoSQL database management system that stores data on disk. It is designed for scalability, flexibility, and high performance, making it suitable for various applications.

 

ArangoDB: ArangoDB is a native multi-model database system supporting key-value, document, and graph data models. It is considered a disk-based database management system as it persistently stores data on disk.

 

Data structures used by in-memory and disk based database management systems

Main memory databases and disk-based databases are different not just because they use different storage methods, but also because they use different data structures to organize and manage data.

 

Data structures used by main memory databases

Hash Tables: These are like quick-access lists used by main memory databases to find data fast.

 

B-Trees: These are special trees used for searching and organizing data in main memory databases. They help to quickly find and change data.

 

Skip Lists: Skip lists are another way to quickly find and change data in main memory databases. They're like smart lists that help organize data efficiently.

 

Arrays and Lists: Main memory databases also use simple structures like arrays and lists to store and manage data easily.

 

Data structures used by disk-based databases

B-Trees: These are like smart trees used by disk-based databases to quickly find data on the disk.

 

Log-Structured Merge Trees (LSM Trees): These are special trees used by disk-based databases to handle lots of new data quickly. They help manage large amounts of data efficiently.

 

Hash Tables with External Chaining: These are like lists used by disk-based databases to organize data on the disk and quickly find what's needed.

 

Sequential Files: Disk-based databases also use simple files to store large amounts of data efficiently.

 

 

In summary

 

a.   Both in-memory and disk-based database systems use the disk, but in-memory databases mostly keep their data in RAM, while disk-based ones store data on the hard disk.

b.   The main issues limiting the growth of in-memory databases are the fact that RAM isn't permanent (meaning it's not always reliable) and the costs involved. Because RAM doesn't hold onto data when the power goes out, problems like software glitches, crashes, hardware breakdowns, or power cuts can cause data loss. Apart from this, RAM can’t hold much data that a hard disk can hold.

c.    Disks are easier to maintain and are much cheaper.

 

                                                  System Design Questions

Volatile and Non-volatile memory

 

Volatile Memory

Both volatile and non-volatile memory are super important in computers. Volatile memory is like a sticky note - it holds information temporarily and loses it when the power is turned off. It's super-fast because it uses simple electronic circuits. There are two main types of volatile memory:

1.   RAM and

2.   Cache memory

 

RAM (Random Access Memory): RAM is the most common type of volatile memory. It's like your computer's short-term memory, holding onto data and instructions that the CPU is currently using. It's really fast to read from and write to, but it's also costly and can't hold as much as non-volatile memory.

 

Cache Memory: Cache memory is like your computer's ultra-quick brain. It's even faster than RAM and is located close to the CPU. Its job is to hold onto data and instructions that are used often, so the computer doesn't have to go searching for them every time. Cache memory is smaller in capacity as compared to RAM.

 

Non-volatile memory

Non-volatile memory sticks around even when the computer is off, acting like a long-term storage unit. It's perfect for holding onto data you need for a while. But unlike volatile memory, it's not as speedy. The main types are:

 

1.   Hard Disk Drives (HDDs)

2.   Solid State Drives (SSDs)

3.   Flash Memory

4.   ROM

 

HDD (Hard Disk Drive): This is a classic storage device that uses magnetic disks to save data. HDDs can hold a lot of data at a lower cost, but they take longer to access information.

 

SSD (Solid State Drive): SSDs are a newer type of storage that uses flash memory chips. They're much faster than HDDs, but they can be more expensive for the same amount of storage space.

 

Flash Memory Cards: These are small storage devices like SD cards and USB drives. They're convenient for carrying data around, but they might not hold as much data and can wear out over time with heavy use.

 

ROM (Read-Only Memory): ROM is a type of memory that stores data that can't be changed. It's used for things like storing essential instructions for starting up a computer or firmware for devices.

 

In short, volatile memory is for storing data temporarily and for faster access, while non-volatile memory is for keeping data long-term, even when the power is off.

 

You can explore a visual representation and comparison of disk and memory access latencies, along with various other relevant figures from different years, by visiting https://people.eecs.berkeley.edu/~rcs/research/interactive_latency.html

 


 

 

                                                  System Design Questions

Wednesday, 28 February 2024

OpenCV: Compute histogram for pixel intensities in BGR images

Using histogram, we can visualize the distribution on pixel intensities in an image.

 

Using cv2.calcHist method, we can compute histogram from an image or specific portion of the image.

 

Why histogram needed?

Using histogram, we can visualize the distribution on pixel intensities in an image.

 

Signature

cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])

 

Following table summarizes the parameters of calcHist method.

 

Parameter

Description

images

It is a list of source images from which you want to calculate the histogram.

channels

Specifies which color channels of image you want to consider while calculating histogram.

 

For a grayscale image, it is set to [0].

 

For a BGR image, you can specify [0], [1], or [2] for the blue, green, and red channels.

mask

It is used to calculate histogram for specific region in the image. This is set to None, if you want to calculate histogram for entire image.

histSize

Specifies number of bins in the histogram.

ranges

Specify range of pixel values in each channel.

 

For grayscale images, it is usually [0, 256] to cover the full range of pixel values.

 

For color images, you might use [0, 256] for each channel.

hist

This is optional, specifies an output parameter where the calculated histogram is stored

accumulate

This is optional parameter. If set to True, the histogram is not cleared in the beginning but is accumulated. This can be useful when you want to calculate histograms for multiple images and accumulate them.

 

Example

image = cv.imread('flowers.jpeg')

colors = ('b', 'g', 'r')
for index, color in enumerate(colors):
    hist = cv.calcHist([image], [index], None, [256], [0,256])
    plt.plot(hist, color=color)
    plt.xlim([0, 256])

 

Above snippet calculate the histogram for all the three color channels.

 

Find the below working application.

 

bgr_image_histogram.py

 

import cv2 as cv
import matplotlib.pyplot as plt

image = cv.imread('flowers.jpeg')

colors = ('b', 'g', 'r')
for index, color in enumerate(colors):
    hist = cv.calcHist([image], [index], None, [256], [0,256])
    plt.plot(hist, color=color)
    plt.xlim([0, 256])

cv.imshow('Image', image)
plt.title('Histogram for image')
plt.xlabel('bins')
plt.ylabel('Number of Pixels')
plt.xlim([0, 256])

plt.show()
cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

 

Output

Original image

 



Histogram



Previous                                                    Next                                                    Home

Monday, 26 February 2024

Pandas: Working with multi indexes

Multi indexing is a feature, where we have multi levels of indexing to get better performance while processing the data.

 

I am using below data set to demonstrate the example.

    Year  Quarter  Sales       City
0  2020        1    100  Bangalore
1  2020        2    150  Bangalore
2  2020        3    115  Bangalore
3  2021        1    120  Hyderabad
4  2021        2    180  Hyderabad
5  2021        3     90  Hyderabad
6  2022        1    130    Chennai
7  2022        2    160    Chennai

 

Set the Year and Quarter columns as indexes

df.set_index(['Year', 'Quarter'], inplace=True)

In this example, we create a DataFrame with four columns: 'Year', 'Quarter', 'Sales' and 'City'. We then set the multi-index by passing a list of column names ['Year', 'Quarter'] to the set_index() method. The inplace=True parameter modifies the DataFrame in place, setting the multi-index.

 

After setting the index, dataset will be changed like below.

               Sales       City
Year Quarter                  
2020 1          100  Bangalore
     2          150  Bangalore
     3          115  Bangalore
2021 1          120  Hyderabad
     2          180  Hyderabad
     3           90  Hyderabad
2022 1          130    Chennai
     2          160    Chennai

As you see above output, the resulting DataFrame has a multi-level index, where 'Year' and 'Quarter' serve as the levels of indexing.

a.   'Year' column is used for Level 0 index

b.   'Quarter' column is used for Level 1 index

 

 

Extract the 3rd quarter results for the year 2020

Each row is uniquely identified by its (Year, Quarter) combination.

 

quarter_3_results_for_2020 = df.loc[(2020, 3)]

 

Above snippet return all the columns associated with the Year 2020 and Quarter 3.

 

Find the below working application.

 

multi_index_hello_world.py

import pandas as pd

# Create a sample DataFrame
data = {'Year': [2020, 2020, 2020, 2021, 2021, 2021, 2022, 2022],
        'Quarter': [1, 2, 3, 1, 2, 3, 1, 2],
        'Sales': [100, 150, 115, 120, 180, 90, 130, 160],
        'City': ['Bangalore', 'Bangalore', 'Bangalore', 'Hyderabad', 'Hyderabad', 'Hyderabad', 'Chennai', 'Chennai']
        }
df = pd.DataFrame(data)
print('Original DataFrame\n', df)

# Set Year and Quarter as indexes
df.set_index(['Year', 'Quarter'], inplace=True)
print('\nAfter setting index columns Year and Quarter\n',df)

# Access data using the multi-index
quarter_3_results_for_2020 = df.loc[(2020, 3)]
print('\nquarter_3_results_for_2020\n',quarter_3_results_for_2020)

 

Output

Original DataFrame
    Year  Quarter  Sales       City
0  2020        1    100  Bangalore
1  2020        2    150  Bangalore
2  2020        3    115  Bangalore
3  2021        1    120  Hyderabad
4  2021        2    180  Hyderabad
5  2021        3     90  Hyderabad
6  2022        1    130    Chennai
7  2022        2    160    Chennai

After setting index columns Year and Quarter
               Sales       City
Year Quarter                  
2020 1          100  Bangalore
     2          150  Bangalore
     3          115  Bangalore
2021 1          120  Hyderabad
     2          180  Hyderabad
     3           90  Hyderabad
2022 1          130    Chennai
     2          160    Chennai

quarter_3_results_for_2020
 Sales          115
City     Bangalore
Name: (2020, 3), dtype: object

 

 

Previous                                                 Next                                                 Home