Open In App

Create Pandas Dataframe Dictionary With Tuple As Key

Last Updated : 27 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, Pandas is a powerful data manipulation library, and a dataframe is a data structure. In this article, we will explore how to create a Pandas Dataframe Dictionary with Tuple as a Key.

What is a data frame?

Dataframes are a fundamental data structure. A data frame is a two-dimensional data structure or tabular data structure with labelled axis rows and columns. It is mainly used for storing and manipulating tabular data. In simple words, it is similar to an Excel spreadsheet or SQL table with rows and columns. It is very useful for analyzing the data.

What do you mean by tuple as key?

In Python, Tuple is an immutable data structure and an ordered collection of elements. Tuple as key means we use tuples as keys in the dictionary.

Mainly, we use a tuple as a key, where a composite key uniquely identifies values.

Example

Python




d={(7,18,14):"Cricket"}
print(d)


Output:

{(7, 18, 14): 'Cricket'}

In this example (7,8,14) is a tuple stored as a key in the dictionary.

Create Pandas Dataframe Dictionary With Tuple As Key

Let’s understand how to create a Pandas Dataframe Dictionary With Tuple as a key for example. I have created two sample dataframes first is to store student basic information and the second is to store grade information we create a new dictionary dataframe where tuples serve as keys to uniquely identify each dataframe.

Step 1: Import Pandas

First, we need to import pandas into our program.

Python




import pandas as pd


If pandas are not installed in your system first install the pandas by using “pip install pandas”

Step 2: Create Sample Data

Here, the dictionary data has tuples as keys and dictionaries as values. Each key-value pair in the dictionary represents information about an individual.

Python3




data = {
    ('Alice', 25): {'City': 'New York', 'Occupation': 'Engineer'},
    ('Bob', 30): {'City': 'San Francisco', 'Occupation': 'Data Scientist'},
    ('Charlie', 22): {'City': 'Los Angeles', 'Occupation': 'Student'}
}


Step 3: Creating a DataFrame from the dictionary

Python3




df = pd.DataFrame.from_dict(data, orient='index')
 
# Displaying the DataFrame
print(df)


Output:

                     City      Occupation
Alice 25 New York Engineer
Bob 30 San Francisco Data Scientist
Charlie 22 Los Angeles Student

Each row in the DataFrame corresponds to an individual (identified by the index, which is a tuple), and the columns represent the attributes ‘City’ and ‘Occupation’ with their respective values.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads