Issue
I have a DataFrame where the first column represents a Color and the second represents the Description of an item. Unfortunately, some of the information of Color
column were combined into the Description
column as you can see below:
data = {"Color": [None, "Red", "Blue", "Green", None],
"Description": ["Red T-Shirt", "Skirt", "Pants", "Underwear", "Blue Cap"]}
df = pd.DataFrame(data)
| Color | Description |
|-------|-------------|
|None |Red T-Shirt |
|Blue |Pants |
|Green |Underwear |
|None |Blue Cap |
First I splitted the Description
column on space with:
df["Description"] = df["Description"].apply(lambda x: x.split(" "))
And what I wanted to do is replace None
values on Color
with first element of Description
where Color is None
. The code I used was:
colors = ["Red", "Blue", "Green"]
df["Color"] = df["Color"].where(df["Color"] != None, df["Description"][0])
df["Color"] = df["Color"].apply(lambda x: x if x in colors else "Color N/A")
My code is returning follow information:
| Color | Description |
|-------|------------------|
|None |["Red", "T-Shirt"]|
|Blue |["Pants"] |
|Green |["Underwear"] |
|None |["Blue", "Cap"] |
But should return:
| Color | Description |
|-------|------------------|
|Red |["Red", "T-Shirt"]|
|Blue |["Pants"] |
|Green |["Underwear"] |
|Blue |["Blue", "Cap"] |
Any idea which mistake I did?
Solution
Try this -
Split the 2nd column based on space character, and then use np.where to fill the Null values in column 'Color'.
df['Description'] = df['Description'].str.split(' ')
df['Color'] = np.where(df['Color'].isna() , df['Description'].str[0], df['Color'])
print(df)
Answered By - Nk03
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.