Python lesson
Splitting text
Each name was cut at the space: Ada Obi became Ada and Obi, and .str[0] kept Ada. Product codes like EAR-BLK-01 split the same way, at the dashes.
Try this lesson free →Example
.str.split() cuts each value at a separator into parts. .str[0] picks the first part, .str[1] the second:
df["First"] = df["Customer"].str.split(" ").str[0]
dfCustomer City First
0 Ada Obi Lagos Ada
1 Tunde Bakare Abuja Tunde
2 Grace Eze Lagos Grace
3 Musa Bello Kano MusaKey points
.str.split(" ")Cut each value at the separator into a list of parts.
.str[0]The first part. .str[1] is the second, .str[-1] the last.
Codes too"EAR-BLK-01".split("-") gives EAR, BLK and 01.
Save itdf["First"] = ... keeps the part as a new column.
Split with .str.split("-"), then pick a part with .str[0].
Practice
1. Build a line that adds a First column with each customer's first name.
df["First"] = df["Customer"].str.split(" ").str[0]2. Add a column called Last with each customer's last name, then show df.
df["Last"] = df["Customer"].str.split(" ").str[1]
df3. In skus, add a column called Product with the first part of each SKU (like EAR).
skus["Product"] = skus["SKU"].str.split("-").str[0]4. In skus, add a column called Size with the last part of each SKU (like 01).
skus["Size"] = skus["SKU"].str.split("-").str[-1]5. SKU codes look like EAR-BLK-01: product, colour, then size. Show the total quantity sold for each colour.
skus["Colour"] = skus["SKU"].str.split("-").str[1]
skus.groupby("Colour")["Qty"].sum()Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →