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 (160x220 cm, Dark Grey) |
Fur Rugs in White - 55x80 cm |
My expected outcome can be like this. Thanks for your support.
------------Product--------------- | -------- Color ------ |
---|---|
youth room (160x220 cm, Dark Grey) | Dark Grey |
Fur Rugs in White - 55x80 cm | White |
CodePudding user response:
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: