Getting The Colors of the Product from the DataFrame

Question:

I couldn’t figure it out to strip the color of the products below. If you help me to do that I appriciate it. I was working on a pandas data frame. Here is the product column and I want to strip and build new column just from the colors. This column is just an example from my data set. There are different types of products with different colors.

————Product—————
youth room (160×220 cm, Dark Grey)
Fur Rugs in White – 55×80 cm

My expected outcome can be like this. Thanks for your support.

————Product————— ——– Color ——
youth room (160×220 cm, Dark Grey) Dark Grey
Fur Rugs in White – 55×80 cm White
Asked By: Orhan Dağ

||

Answers:

You will surely need a list (or any other collection) of the expected colors. Something like this:

colors = ["Blue", "Red", "Green", "Dark Grey", "White", "Black"]

When you have this defined, the filtering is pretty straightforward.
Here you can find a code example:

import pandas as pd

# Sample data
example_data = {'Product': ['youth room (160x220 cm, Dark Grey)', 
                            'Fur Rugs in White - 55x80 cm',
                            'Red Modern Chaiselong (120x120 cm)', 
                            'Classic 100x20 cm Armchair Green']}

# Create df with sample data
example_df = pd.DataFrame(example_data)

# List comprehension to find the expected colors in the "Product" column values
example_df['Color'] = example_df['Product'].apply(lambda row: "".join([color for color in expected_colors if color in row]))

Which will give us the following output dataframe:

enter image description here

Answered By: marinovik
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.