0
0
Pandasdata~15 mins

map() for element-wise transformation in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Using map() for Element-wise Transformation in pandas
📖 Scenario: You work in a small bookstore. You have a list of books with their genres. You want to create a new column that shows a short code for each genre to make your data easier to read.
🎯 Goal: Build a pandas DataFrame with book titles and genres, then use map() to create a new column with genre codes.
📋 What You'll Learn
Create a pandas DataFrame called books with columns 'Title' and 'Genre' using the exact data provided.
Create a dictionary called genre_codes that maps each genre to its short code.
Use the map() function on the 'Genre' column to create a new column called 'GenreCode'.
Print the books DataFrame to show the new column.
💡 Why This Matters
🌍 Real World
Mapping long or complex category names to short codes helps in reports, dashboards, and data storage.
💼 Career
Data analysts and scientists often use map() to clean and prepare data for analysis or visualization.
Progress0 / 4 steps
1
Create the books DataFrame
Create a pandas DataFrame called books with two columns: 'Title' and 'Genre'. Use these exact entries: 'The Hobbit' with 'Fantasy', '1984' with 'Dystopian', 'To Kill a Mockingbird' with 'Classic', 'The Great Gatsby' with 'Classic', and 'Brave New World' with 'Dystopian'.
Pandas
Need a hint?

Use pd.DataFrame with a dictionary where keys are column names and values are lists of data.

2
Create the genre_codes dictionary
Create a dictionary called genre_codes that maps the genres to short codes exactly as follows: 'Fantasy' to 'FAN', 'Dystopian' to 'DYS', and 'Classic' to 'CLA'.
Pandas
Need a hint?

Use curly braces {} to create a dictionary with the exact key-value pairs.

3
Use map() to create the GenreCode column
Use the map() function on the 'Genre' column of the books DataFrame with the genre_codes dictionary to create a new column called 'GenreCode'.
Pandas
Need a hint?

Use books['Genre'].map(genre_codes) to transform the genres into codes.

4
Print the books DataFrame
Print the books DataFrame to display the new 'GenreCode' column alongside the original data.
Pandas
Need a hint?

Use print(books) to show the DataFrame with the new column.