…
…
Statistics and Data Analysis Fundamentals · Lesson 6 / 44 · DataFrames and selecting
PreviewIn this lesson you will
np.where, and loc; work with a text column through .str and a date column through pd.to_datetime and .dtperiod and discounted columns to answer "Did the share of discounted orders change after May?"You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The manager asked "Sales dropped, why?" and you turned it into smaller questions: in which month did the drop start, how do the months before and after May differ, and did discounted orders increase? None of these answers sits in orders.csv as a ready column, because date is plain text and there is no month, period, or "discounted or not" information. In this lesson you will build these breakdowns yourself from the columns that already exist.
By the end of the lesson, you will have added these columns next to the table and made a one-line comparison:
Output date month period discounted discount_amt
0 2026-01-01 1 before False 0.0
1 2026-01-02 1 before False 0.0
2 2026-01-02 1 before False 0.0
...
Discounted order share: before 0.173 · after 0.245Raw data rarely arrives ready for analysis. When the system saves an order, it writes the date, the amount, and the discount rate. It does not keep a separate column for "is this order after May?" or "is this order discounted?". Yet analysis questions are often asked with exactly this kind of column. This is why a large part of data analysis is deriving new columns from existing ones.
In this lesson you will:
np.where.In lesson 4, you did a calculation with all the values of a column in one line: df["amount"] / 1.20 produced a Series with the amount without tax for every row. Instead of looking at that Series on the screen and leaving it, one assignment writes it into the table:
The calculation and the condition sit side by side in the same table: we round the amount without tax to two decimals and label large and small orders.
import pandas as pd import numpy as np df = pd.read_csv("orders.csv") df["ex_tax"] = (df["amount"] / 1.20).round(2) df["size"] = np.where(df["amount"] >= 100, "large", "small") print(df[["amount", "ex_tax", "size"]].head(3)) print(df["size"].value_counts())
Output amount ex_tax size
0 249.90 208.25 large
1 74.95 62.46 small
2 164.95 137.46 large
size
small 702
large 183
Name: count, dtype: int64A school library takes the month and the weekend out of its borrowing dates.
import pandas as pd o = pd.DataFrame({ "book": ["Poems", "Novel", "Atlas", "Dictionary", "Novel"], "borrowed": ["2026-02-02", , , , ], }) o[] = pd.to_datetime(o[]) o[] = o[].dt.month o[] = o[].dt.dayofweek o[] = o[] >= 5 (o)
Forgetting `.str` and the conversion to a date. df["device"].upper() raises an error, because upper is a method of a single string, not of a Series. In the same way, if you write df["date"].dt.month directly on the date column that comes from the CSV, you get this error:
OutputAttributeError: Can only use .dt accessor with datetimelike valuesIn plain words: the .dt tool can be used only on values of the date type. The column is still text. The correct way is first df["date"] = pd.to_datetime(df["date"]), then .dt.month; and string methods always go through .str: df["device"].str.upper().
df["new"] = ... with a calculation, a comparison (True/False; its mean gives a share), or np.where(condition, a, b) for two labels. If only a part will change, make the default first, then df.loc[condition, "column"] = value. Chained assignment does not change the table..str: strip, lower, replace, contains, [:n]. Some letters change length, such as German ß, which becomes SS with upper(); use casefold() to compare.pd.to_datetime changes text into a date. .dt.month, .dt.day, and .dt.dayofweek (Monday 0, Sunday 6) give the parts and open the questions "which month" and "is it a weekend".Next lesson: Now every order has a month, a period, and a discount. Questions like "how many orders each month, what average amount in each category" become one line with grouping.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
df["ex_tax"] = df["amount"] / 1.20At Bazaar, the amount is calculated like this: amount = quantity × unit_price × (1 − discount). If the discount rate is 0.2, the customer pays 80 percent of the list price. The difference between the list amount and the amount paid is the discount the store gave, in dollars. These two measures are not in the table, but two columns give them right away.
The result of a comparison can be a column too. In lesson 5, you saw that df["discount"] > 0 is a condition Series that gives True or False for every row. When you write it into the table, you get a "discounted or not" column. True counts as 1 and False counts as 0, so the sum of this column is the number of discounted orders and its mean is their share.
When you need a label with two options, which means one text if the condition is true and another text if it is false, NumPy's np.where(condition, a, b) does the job. In this lesson we use only this one function from NumPy. You call it after the line import numpy as np, and it comes installed together with pandas.
Example 1 (case): List amount, discount amount, discounted or not, size
import pandas as pd import numpy as np df = pd.read_csv("orders.csv") df["list_amount"] = df["quantity"] * df["unit_price"] df["discount_amt"] = df["list_amount"] - df["amount"] print(df.loc[[5, 15], ["quantity", "unit_price", "discount", "amount", "discount_amt"]]) df["discounted"] = df["discount"] > 0 print("Discounted orders:", df["discounted"].sum()) print("Discounted share:", round(df["discounted"].mean(), 3)) df["size"] = np.where(df["amount"] >= 100, "large", "small") print(df["size"].value_counts())
Output quantity unit_price discount amount discount_amt
5 2 449.95 0.2 719.92 179.98
15 1 44.95 0.1 40.46 4.49
Discounted orders: 169
Discounted share: 0.191
size
small 702
large 183
Name: count, dtype: int64Check the first two rows by hand. Order 5 has a list amount of 2 × $449.95 = $899.90. With a 20 percent discount, $719.92 was paid, and the difference is $179.98. In order 15, a $44.95 product was sold for $40.46 with a 10 percent discount. Of 885 orders, 169, or 19.1 percent, are discounted. The 183 orders of $100 and above got the "large" label.
Now change the code yourself: (1) Change the size threshold to 250; the number of large orders should drop to 35. (2) Add one line to make an amount-without-tax column: df["ex_tax"] = df["amount"] / 1.20 and print(df["ex_tax"].head(3).round(2)); the first three values should be 208.25, 62.46, 137.46. (3) Print the mean of the discounted column yourself.
Try it now· not graded; doesn't affect progress
np.where asks every row the same question and puts one of two labels depending on the answer. Watch which rows become "large" as the threshold changes, in a small table of six amounts.
Change the threshold: which amounts get the "large" label?
Pick a value; predict the output first, then look.
1import pandas as pd2import numpy as np34t = pd.DataFrame({"amount": [15.95, 44.95, 74.95, 124.95, 249.90, 899.90]})5threshold = 1006t["size"] = np.where(t["amount"] >= threshold, "large", "small")7print(t["size"].tolist())
['small', 'small', 'small', 'large', 'large', 'large']
Faded lines didn't run with this value. The condition is >=, so amounts equal to or above the threshold become "large". As the threshold goes up, fewer rows get the label; at 250, only the $899.90 order is left. The meaning of the label depends completely on the threshold you pick, so you write the threshold in the report too.
locSometimes the value of the new column is different only in some rows. To compare the time before and after May, we want a period column: orders before May are "before", and orders from May 1 on are "after". The most readable way has two steps. First you create the whole column with a default value. Then you change the rows that meet the condition with df.loc[condition, "column"] = value. In lesson 5, you used loc[condition, columns] to select rows and columns. When the same expression is written on the left side, it means "put this in these cells".
Example 2 (case): Period column
import pandas as pd df = pd.read_csv("orders.csv") df["period"] = "before" df.loc[df["date"] >= "2026-05-01", "period"] = "after" print(df["period"].value_counts())
Outputperiod
before 669
after 216
Name: count, dtype: int64date is still text here. The comparison >= "2026-05-01" still works, because the dates are written in year-month-day order with zero padding. As text, alphabetical order is the same as calendar order. You saw this in lesson 5.
The assignment rule. In pandas 3.0, always change a column with one single, complete assignment: df["device"] = df["device"].str.strip() or df.loc[condition, "period"] = "after". Chained assignment, which writes two square brackets one after the other (df[condition]["period"] = ...), does not change the table. The same is true for inplace=True, which you may see in older code. The reason is this: df[condition] returns a new table made of the filtered rows. The assignment goes to that temporary table, and the temporary table disappears right away. Predict the result before you run it.
What does this code print?
df["period"] = "before" df[df["date"] >= "2026-05-01"]["period"] = "after" print(df["period"].value_counts())
.strIn the Python course, you used string methods on one string: "Book".lower() gives "book". A column has hundreds of strings, and you want to apply the same method to each of them. For this, pandas gives you the .str tool: df["category"].str.lower() makes every string in the column lowercase. The ones you will use often are .str.lower() and .str.upper() (letter case), .str.strip() (removes spaces at the start and end), .str.replace("a", "b") (changes a piece), .str.contains("book") (does the string contain this piece?), and .str[:4] (the first four characters).
.str.contains returns True or False for each row. So it is a condition Series, and you can use it to filter as in lesson 5. == gives True only when the whole string is the same. For a search like "names that contain book", you need contains.
Example 3 (case): Searching product names
import pandas as pd p = pd.read_csv("products.csv") books = p[p["product_name"].str.contains("book")] print(books["product_name"].tolist()) is_set = p["product_name"].str.lower().str.contains("set") print(p.loc[is_set, "product_name"].tolist())
Output['Self-help book', "Children's book", 'Science book', 'History book', 'Cookbook', 'Poetry book', 'Exam prep book']
['Keyboard and mouse set', 'Towel set', 'Food storage set', 'Cookware set', 'Makeup set']In the second search, .str.lower() came first and .str.contains("set") came after it. A product name that started with a capital "Set" would be found too. Notice that contains is case-sensitive: contains("Book") with a capital B finds nothing in this table, because no name has a capital "Book". .str is written again at every link of the chain, because lower() returns a new string column, and to call a string method on it you need .str again. What happens if you skip .str?
df["device"] is a string column. What does df["device"].upper() do?
Be careful with letters that are not plain English letters. Accented letters are fine: "Café".upper() gives 'CAFÉ' and "CAFÉ".lower() gives 'café'. But a few letters follow different rules. The German letter ß has no single capital letter, so upper() turns it into two letters: "Straße".upper() gives 'STRASSE'. The string was 6 characters long and became 7. This causes a trap when you compare: "Straße".lower() gives 'straße' and "STRASSE".lower() gives 'strasse'. Two strings that look like the same word are not equal.
What does this code print?
print("Straße".lower() == "STRASSE".lower())
There is also a method called map that changes values with a dictionary. We will come back to it in lesson 20, when we fix spelling differences.
pd.to_datetime and .dtThe date column comes from the CSV as text. pandas does not know that the text "2026-01-01" falls on a Thursday or in January. For pandas it is only a series of characters. pd.to_datetime(df["date"]) changes the text into the date type (datetime64). After the change, you ask for the parts of the date with the .dt tool: .dt.month is the month number (1–12), .dt.day is the day of the month, and .dt.dayofweek is the day of the week. dayofweek counts Monday as 0 and Sunday as 6, the same rule as weekday() from the Python course. So the weekend is the condition dayofweek >= 5.
A month column opens the question "In which month did the drop start?", and a day-of-the-week column opens "Is the weekend busier?". There is also dt.to_period("M"), which gives a year-month label. This course's data covers one year only, so dt.month is enough.
Example 4 (case): Month and weekend share from a date
import pandas as pd df = pd.read_csv("orders.csv") df["date"] = pd.to_datetime(df["date"]) df["month"] = df["date"].dt.month print(df["month"].value_counts().sort_index()) print("Weekend share (%):", round((df["date"].dt.dayofweek >= 5).mean() * 100, 1))
Outputmonth
1 154
2 177
3 176
4 162
5 112
6 104
Name: count, dtype: int64
Weekend share (%): 32.7When you derive the month column, the drop becomes visible. The order count was between 154 and 177 in the first four months, and it falls to 112 in May and 104 in June. sort_index() lined up the counts by month number. Without it, value_counts() would start from the busiest month.
Let's check where dayofweek starts counting with the first order. January 1, 2026 is a Thursday.
Example 5 (case): The day of the first order
import pandas as pd df = pd.read_csv("orders.csv") df["date"] = pd.to_datetime(df["date"]) print(df["date"].iloc[0], df["date"].iloc[0].dayofweek)
Output2026-01-01 00:00:00 3Monday is 0, Tuesday is 1, Wednesday is 2, Thursday is 3. If you think "it starts from 1" or "Sunday is 0", you will write the weekend condition wrong. If a date has no time information, it is taken as midnight (00:00:00).
Now change the month count: (1) Write dt.day instead of dt.month; you see the count by day of the month. (2) Replace the last line with print(df["date"].dt.dayofweek.value_counts().sort_index()); the two busiest days should be Saturday (5: 146) and Sunday (6: 143).
Try it now· not graded; doesn't affect progress
The columns you have derived so far have different types: some are numbers, some are True/False, and some are text. Match each expression with the type of column it produces.
Choose the type of column each expression produces.
For each row, pick its match from the list, then check.
df["quantity"] * df["unit_price"]df["discount"] > 0np.where(df["amount"] >= 100, "large", "small")df["product_name"].str.contains("set")pd.to_datetime(df["date"]).dt.monthNow you can ask the analysis question: did the share of discounted orders change after May? Both columns are derived: period from the date, and discounted from the discount rate. You select the rows of each period with loc and take the mean of the discounted column.
Example 6 (case): Discounted share before and after
import pandas as pd df = pd.read_csv("orders.csv") df["date"] = pd.to_datetime(df["date"]) df["discounted"] = df["discount"] > 0 df["period"] = "before" df.loc[df["date"] >= "2026-05-01", "period"] = "after" before = df.loc[df["period"] == "before", "discounted"].mean() after = df.loc[df["period"] == "after", "discounted"].mean() print("Discounted order share: before", round(before, 3), "· after", round(after, 3))
OutputDiscounted order share: before 0.173 · after 0.245You would tell the manager: "In May and June, one in every four orders is discounted; before, it was about one in six." This number does not say why it increased. Did a campaign start, or was a discount given after a price increase? We do not know. We will look at this in the practice in lesson 10. After you change the date with to_datetime, the comparison >= "2026-05-01" works too; pandas reads the text as a date.
Put the lines of the code that gives the same result in the right order.
Put the code that prints the discounted share after May in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The same tools work in every table. In the six-row order list of a cafe, product names are written in different ways (" Latte", "LATTE", "latte "), and the time is text in the form "08:15". Before asking "How many of each product were sold?" and "What share of the orders is in the morning?", the columns need to be fixed.
Example 7 (outside the case): Cafe orders
import pandas as pd k = pd.DataFrame({ "time": ["08:15", "09:40", "12:05", "14:30", "10:55", "17:20"], "item": [" Latte", "tea ", "LATTE", "Tea", "latte ", "Brownie"], "price": [4.25, 1.25, 4.25, 1.25, 4.25, 3.00], }) print(k["item"].value_counts().size) k["item"] = k["item"].str.strip().str.lower() k["hour"] = k["time"].str[:2].astype(int) k["morning"] = k["hour"] < 12 print(k) print(k["item"].value_counts()) print("Morning share:", round(k["morning"].mean(), 2))
Output6
time item price hour morning
0 08:15 latte 4.25 8 True
1 09:40 tea 1.25 9 True
2 12:05 latte 4.25 12 False
3 14:30 tea 1.25 14 False
4 10:55 latte 4.25 10 True
5 17:20 brownie 3.00 17 False
item
latte 3
tea 2
brownie 1
Name: count, dtype: int64
Morning share: 0.5Before the fix, all six rows counted as a different product. After strip and lower, three products remained. .str[:2] took the first two characters of the time ("08"). This is still text, so we changed it into an integer with astype(int). You will see type conversion in detail in lesson 20; here it only means "turn the text into a number". The Tea became tea without trouble, because plain English letters have no trap like ß.
A number you derive does not prove anything by itself; what you compare it with is what matters. Try a decision scenario with Bazaar's weekend share.
The manager asked "Are there more orders on weekends?" The mean of the dayofweek >= 5 column you derived is 0.327: 32.7 percent of the orders are on weekends. What do you answer?
Pick an option and see what happens. There are no points; you can try the other options too.
Output book borrowed month weekday weekend
0 Poems 2026-02-02 2 0 False
1 Novel 2026-02-07 2 5 True
2 Atlas 2026-02-08 2 6 True
3 Dictionary 2026-03-11 3 2 False
4 Novel 2026-03-14 3 5 TrueFebruary 2, 2026 is a Monday, so weekday is 0; the 7th and the 14th are Saturdays (5), and the 8th is a Sunday (6).