Python lesson
Your own rule on every row
Each order's revenue went through size(): 140 and 105 are Large, 70 is Medium, the rest Small. np.where only gives two outcomes. A function can give as many as the rule needs.
Try this lesson free →Example
Write the rule once as a function, then .apply runs it on every value in the column:
def size(revenue):
if revenue >= 100:
return "Large"
elif revenue >= 50:
return "Medium"
else:
return "Small"
df["Size"] = df["Revenue"].apply(size)
dfOrder Day Store Product Qty Revenue Size
0 O101 Mon Lagos Earbuds 2 70 Medium
1 O102 Mon Abuja Charger 1 15 Small
2 O103 Tue Lagos Phone case 3 24 Small
3 O104 Wed Lagos Earbuds 1 35 Small
4 O105 Wed Abuja Earbuds 4 140 Large
5 O106 Thu Lagos Charger 2 30 Small
6 O107 Fri Abuja Phone case 5 40 Small
7 O108 Fri Lagos Earbuds 3 105 LargeKey points
def size(revenue):The rule, for one value. return sends back the answer.
.apply(size)Run the function on every value. No brackets after size.
Why not np.where?np.where gives two outcomes. A function can give three or more.
df["Size"] = ...Save the answers as a new column.
Write the rule as a function, then df["Size"] = df["Revenue"].apply(size).
Practice
1. Build a line that adds a Size column using the size function.
df["Size"] = df["Revenue"].apply(size)2. Use the size function to add a Size column, then show df.
df["Size"] = df["Revenue"].apply(size)
df3. Write a function pack(qty) that returns Bulk for 3 or more items and Single otherwise. Add a Pack column with it.
def pack(qty):
if qty >= 3:
return "Bulk"
else:
return "Single"
df["Pack"] = df["Qty"].apply(pack)4. Write a function size(revenue) that returns Large from 100, Medium from 50 and Small below. Add a Size column, then count each size.
def size(revenue):
if revenue >= 100:
return "Large"
elif revenue >= 50:
return "Medium"
else:
return "Small"
df["Size"] = df["Revenue"].apply(size)
df["Size"].value_counts()5. Delivery costs 5 on orders under 50, and it's free from 50 up. Add a column called Delivery with each order's fee.
def fee(revenue):
if revenue < 50:
return 5
else:
return 0
df["Delivery"] = df["Revenue"].apply(fee)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 →