How to Create a Dataframe Based On a Reference Map in Python

A reference map is essentially a dictionary that maps keys to values. To create a dataframe based on a reference map in Python, you can use the from_dict() function.

The following example shows how to create a dataframe based on a reference map in Python.

Using from_dict() Function

We can use the from_dict() function to create a dataframe based on a reference map.

Suppose we have the following dataframe:

# Import pandas library
import pandas as pd

# Create dataframe
df = pd.DataFrame({
    'Time': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
    'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
    'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
    'Price': [4500, 550, 250, 50, 350, 50],
    'Status': [1, 1, 1, 0, 1, 1]
})

# Declare reference map
ref_map = {'A-101': 'Laptop', 'A-102': 'Mobile', 'B-102': 'Scanner'}

# Create new dataframe
new_df = pd.DataFrame.from_dict(ref_map, orient='index', columns=['Product_Name'])

# Filter data from new dataframe
new_df = new_df[new_df.index.isin(df[df['Price'] > 2000]['Product_Code'])]

# Show new dataframe
print(new_df)

Output: 👇️

      Product_Name
A-101       Laptop

In this example, we use the from_dict() function to create a new dataframe new_df from the reference map ref_map.

We then filter the new dataframe to include only the rows where the product code is in the original dataframe df and the price is greater than 2000.

The output shows the new dataframe created from the reference map.

Conclusion

We can use the from_dict() function to create a dataframe based on a reference map in Python.