Python for Data Analysis
With pandas, most questions about a table are one line of code, and that line always returns a number. It does not know whether the file had blank cells, whether a price was stored as the word "None", whether a date of 1 January 1900 was real or a placeholder, or whether half of one group’s records were missing. It computes anyway, and a wrong answer looks exactly like a right one. So data analysis is less about the computing line than about what comes before it: what one row stands for (the grain), what types the columns have, which values are wrong, disguised, or impossible, and what a blank means — zero, unknown, or not applicable. Those three readings can put an average a factor of two apart, and no error message raises the question for you.
Two ideas then carry the computing itself. Vectorized thinking says what happens to a whole column, not to each row: amount = boxes * price applies to every row at once, in compiled code, and reads like the sentence it implements. Split, apply, combine is the shape of every question with the word per in it, and groupby does all three steps; the skill is choosing between an aggregate, which shrinks the table to one row per group, and a transform, which keeps every row and puts the group’s value beside it. Around both sits the habit the session is built on: inspect first — shape, types, a few rows, blanks, ranges, distinct values — clean with a short list of explicit rules that make a value missing but never delete a row silently, and report what was left out, with counts.

Listen
| Speaker | Text |
|---|---|
| Alex | So you’re staring at your screen. You are a graduate student in data science and analytics, and well, you’ve finally done it. |
| Sam | You’ve written the perfect line of Python code. |
| Alex | Exactly. You run your algorithm and out pops this beautiful, crisp, just highly formatted number, like 2 decimal places, no error messages. It looks absolutely authoritative. |
| Sam | Oh, it feels like an incredible victory. You know, you have your result, you copy it right into your slide deck, and you are fully prepared to present it to the stakeholders as ground truth. |
| Alex | But, and here is the chilling scenario we are going to explore today. What if that perfectly formatted number is completely fundamentally wrong, right? |
| Sam | And not because your code crashed. |
| Alex | Exactly, not because it crashed, but because the line of code you just wrote has absolutely no idea that the data it processed is a complete illusion. |
| Sam | That is the ultimate trap of data analysis, and honestly, it catches incredibly smart people all the time. A wrong answer in Python looks identical to a right one. |
| Alex | Yeah, it has the exact same format, the same number of decimals, and absolutely no error message to warn you that you’ve just made a massive mistake. So today’s deep dive is tailored specifically for you, the data science student who is, you know, eager to write code, run algorithms, and generate those insights. We’re looking at a set of source materials titled Lecture Notes Session 8, Python for Data Analysis. |
| Sam | And I mean, textbooks will teach you the syntax, right? But our mission today is to look at what has to happen before the computation, |
| Alex | right? We are going to explore how you actually understand a table, how you verify messy data, and uh how you translate vague business questions into reliable operations, |
| Sam | because escaping that trap we just talked about. It requires a total shift in mindset. Like, before we even consider which Python package to import. We have to acknowledge the reality of the files we’re dealing with, yeah, |
| Alex | the real world files, |
| Sam | exactly, |
| Alex | not the clean ones. |
| Sam | Exactly. In a classroom environment, you often get this clean, perfectly curated CSV file where everything aligns perfectly. But in the real world, data arrives in total chaos. |
| Alex | Oh, complete chaos. Like it’s a messy export from some legacy sales system built in the 90s |
| Sam | where it consists of records that were manually typed in by, you know, tired shift workers at 2 in the morning, |
| Alex | right? Or it’s a bulk download from a public agency where half the critical fields were just left optional |
| Sam | and a standard line of Python doesn’t know any of that context. |
| Alex | It really doesn’t. It doesn’t know if a date listed as, say, January 1st, 1900 is a historical fact because you’re analyzing the industrial revolution, |
| Sam | or if it’s just a default placeholder, right, like some frustrated employee just selected the first thing from a dropdown menu. |
| Alex | Exactly, and it doesn’t know if the word none is a descriptive text string for a product or if it’s a genuinely missing value. It just takes whatever is in that cell and computes it anyway. |
| Sam | Which brings us to the most fundamental structure in this entire field, which is the table. I mean, you already know what a data frame is. You know that rows are observations and columns are variables, |
| Alex | right? That’s the basics. |
| Sam | But the very first question you must ask of any table, like before you write a single line of code, is much deeper than that. You have to define the table’s |
| Alex | grain. The grain. I actually want to spend a second on this because I think it’s a concept that gets glossed over when we are, you know, just rushing to run machine learning models. |
| Sam | Oh, absolutely. The grain is simply the definition of what one single row stands for. |
| Alex | Like, what does this row actually represent |
| Sam | exactly? You have to ask yourself, is this row one complete customer order? Or is it just one single line item within a larger order, right? |
| Alex | Does a row represent one unique customer, or does it represent one individual visit by a customer who, I don’t know, might be in this table 50 times? |
| Sam | And treating plain Python like a calculator before you answer that question is incredibly dangerous. Well, |
| Alex | because a physical calculator never looks up at you and says, Wait, this input is garbage. |
| Sam | No, it just confidently spits out the wrong output. Yeah, |
| Alex | it just does the math. If you don’t define the grain, the math basically becomes a weapon against you. Like, let’s say you have a table where every row is a line item in an online shopping cart, and there’s a column for the total freight cost of the order, say $50 |
| Sam | right? So if you sum that freight cost column to find out how much the company spent on shipping |
| Alex | and the order had 10 line items, |
| Sam | you just added that $50 charge 10 separate times. |
| Alex | Exactly. You’ve just reported $500 in shipping for a single $50 box. |
| Sam | It’s a disaster. Every count and every average you run depends entirely on the grain. Like if you misunderstand what a row represents, your entire analysis is flawed from the exact moment you hit execute, no matter how elegant your code is. |
| Alex | So, OK, we established the grain. We know exactly what our rows represent. Now we have to actually manipulate them. And this is where we leave the tedious bookkeeping of plain Python behind and move to the power tools, right? Pandas and numpai. |
| Sam | Yeah, these packages are the absolute foundation of modern data science in Python. I mean, PANDAS gives us the architectural structures, so the data frame for tables and the series for single columns, |
| Alex | right? It handles reading those messy files, joining tables together, selecting data, |
| Sam | exactly. And underneath PANDAS is Numpai, which is the mathematical engine. Like NumPy is built to handle incredibly fast arithmetic on entire arrays of numbers. |
| Alex | And just a quick note, by universal convention, you always import pandas as PD and numpii as NP. Doing anything else makes your code look, well, incredibly suspicious to any other professional reviewing your work. |
| Sam | It really is the secret handshake of the industry, but You know, the real magic isn’t the import statement. It’s how these tools fundamentally change your workflow, because in plain Python, a table is essentially just a list of dictionaries. Oh, |
| Alex | yes, which means answering a simple business question requires this massive amount of mental overhead, |
| Sam | right? You have to write a loop. You have to create an empty dictionary to hold your running totals. |
| Alex | You have to check if a customer’s name is already in that dictionary, add their new total if they are, or like create a new key if they aren’t. You’re just constantly managing loop variables, |
| Sam | and the source notes provide a perfect illustration of this with this small farm delivering boxes of produce. The farm owner simply wants to know the total revenue generated per customer. Sounds so simple. It does, but doing that in plain Python requires about 15 lines of loop code. Like you have to iterate through every delivery, extract the customer name, extract the amount, check your running total dictionary, |
| Alex | update it, handle any potential errors. |
| Sam | It is so tedious and it is incredibly easy to introduce a really subtle bug that just ruins the total. |
| Alex | But in pandas, that exhausting loop entirely disappears. It collapses into a single line of code. You just write deliveries.group by customer amount.sum. That’s it. That’s the entire operation. It’s beautiful. And that collapse introduces the second core concept for a data scientist, which is vectorized thinking. You have to stop telling the computer what to do to each individual row one by one, right? |
| Sam | You have to start dictating what happens to an entire column simultaneously. |
| Alex | I actually want to try an analogy here because this was a huge light bulb moment for me. OK, let’s hear it. So writing a loop across the rows of a table is kind of like a manager micromanaging every single employee in a massive corporation. The manager walks to desk one, gives an instruction, waits for it to be done, then walks to desk two, gives the exact same instruction, waits. That sounds exhausting, right? But vectorization is like stepping up to a company-wide PA system and broadcasting a single memo that every single employee executes instantly and simultaneously. |
| Sam | I love that. That analogy captures the mechanics perfectly. Because under the hood, NumPy is basically allocating contiguous blocks of memory and running highly optimized C code to execute that PA announcement. Yeah, because it doesn’t have to translate Python instructions row by row, it is hundreds, sometimes thousands of times faster than a Python loop when you’re dealing with millions of rows. |
| Alex | And I mean, fast code is great, but the notes argue that speed is actually the smaller benefit of vectorization, which it feels kind of counterintuitive when we are dealing with massive data sets. |
| Sam | I know it does. The speed is a massive technical benefit, sure, but the larger benefit is for you, the analyst. The true power is readability and reducing your cognitive load. Uh, OK. Yeah, when you write a vectorized operation like, say, deliveries amount equals deliveries boxes times deliveries price per box, there is no loop. There’s no dictionary of running totals. |
| Alex | The code reads exactly like the English sentence it implements. The amount is the boxes times the price. |
| Sam | Exactly. You stop being a bookkeeper tracking loop variables, and you free up your brain to actually think about the data itself. |
| Alex | It totally removes the friction between the business logic and the code. And if the business logic has a condition attached, well, we can still stay vectorized. The sources mention using numpi functions like NP.ware. Yeah, |
| Sam | NP.ware is fantastic. You can dictate complex logic right at the column level. So you can say nP.ware, the number of boxes is greater than or equal to 4. Apply a 10% discount. Otherwise keep the normal amount. |
| Alex | And it just broadcasts that conditional logic down the entire column in a fraction of a second. |
| Sam | Exactly. The habit you absolutely must build as a grad student is this. The moment your figures start typing for row in table, you need to stop. Pull your hands off the keyboard, and ask yourself what column level sentence you are actually trying to write. So |
| Alex | this PA system analogy is great if we want to give every single row the exact same instruction, but you know, business doesn’t really work like that. |
| Sam | No, it rarely does. |
| Alex | Stakeholders rarely ask for the total revenue of the entire universe of data. They want to see how the East Coast is doing compared to the West Coast. So how do we send different memos to different groups without sliding backward and writing messy loops again? Well, |
| Sam | this is where we hit concept number 3, and there is a magic keyword you have to train your ear to catch. Whenever a stakeholder asks you a question. Listen for the word |
| Alex | per, total sales per region. |
| Sam | Average delivery time per driver. |
| Alex | Yes. |
| Sam | Every time you hear that word, the operation requires the exact same three steps split, apply, combine. |
| Alex | Split, apply, combine. OK, break that down for |
| Sam | us. So first you split the rows into separate groups based on the category. So a pile for the east coast, a pile for the West Coast. Second, you apply a calculation to each of those independent piles. And third, you combine those separate results back into a single neat table. |
| Alex | And PANDAS handles all three of those steps simultaneously with that group by function we mentioned earlier. But knowing to use group by is really only half the battle. |
| Sam | It is. The real complexity lies in the apply step. The calculation you perform on those groups comes in 3 distinct flavors. Basically, you have aggregate, transform. And filter and mastering the difference between these three is the dividing line between a novice and a professional pandas user. |
| Alex | OK, so let’s make this actionable. I am staring at a business request. I know I need to group the data by region. How do I logically determine if my next move is an aggregate, a transform, or a filter? |
| Sam | The source material provides a brilliant, highly practical heuristic for this. You simply ask yourself how many rows should the final answer have. |
| Alex | How many rows? OK, so if my stakeholder wants the total monthly sales per region, my massive table of a million individual transactions needs to shrink down. I basically just want one row for the East Coast total, one row for the West Coast total. |
| Sam | Exactly, because the answer should have one row per group. You need to aggregate. Aggregation is the act of summarizing. You know, you are crushing millions of rows down into a single representative number for that category. But |
| Alex | what if the stakeholder asks a totally different question? Like, what if they want to know what percentage of the East Coast total daily sales came from one specific transaction? I can’t shrink the table down then because I need to attach that new percentage to every single original line item. |
| Sam | Right? In that scenario, the final answer needs to have the exact same number of rows as the original table. So when you need to preserve the shape of the data, you transform, transform, OK, yeah, transform calculates the group total quietly in the background and then it broadcasts that total back to every individual row in that group. It allows you to do row level math against a group level metric. |
| Alex | So transform keeps the shape, aggregate shrinks the shape. |
| Sam | You got it. And finally, there are times you want to keep the original rows entirely unchanged, but only for certain groups like what? Like a stakeholder might say, show me all the transaction records, but only for customers who have placed at least 5 orders historically. Oh, OK. So you are using a group level metric, total orders per customer, to decide whether to keep or drop the individual rows. That is a filter. By asking how many rows the output should have, the required pandas method becomes instantly obvious. |
| Alex | Aggregate shrinks, transform preserves, filter drops. OK. We have a robust toolkit for manipulating the data that exists, but now I really want to address the elephant in the room. What do we do when the data simply isn’t there? Yeah, that’s the |
| Sam | big one. We shift our mindset from manipulating values to interrogating absences. Concept 4 is realizing that a missing value is not an empty space. A missing value is a loud, glaring question. Uh, |
| Alex | I’m going to play devil’s advocate for a second here though. Pandas has a default behavior when it encounters missing data, right? Like a non value. If you ask for a sum or an average, pandas just skips the missing values entirely. It acts like those rows don’t even exist. Isn’t that the mathematically safe thing to do? Like, if we don’t have the data, we shouldn’t invent it, right? |
| Sam | Well, that assumes a blank space is a statistical void, but in reality, a blank space is usually a record of human behavior. |
| Alex | Oh, that’s interesting. |
| Sam | Yeah, let’s use the farm delivery scenario from the notes. So the farm owner asks drivers to start recording the tip they receive on a clipboard. You digitize the clipboard, you look at the data, and 4 out of the 8 tip cells are completely blank. |
| Alex | OK, so if you let pandas use its default behavior and skip the blanks, it basically averages the 4 recorded tips and tells you the average tip is $3. |
| Sam | Exactly. But a blank tip cell probably doesn’t mean the data was just lost in the ether. It almost certainly means the customer handed the driver $0 and the driver just didn’t bother to write down a 0 because |
| Alex | they’re in a hurry. So if you fill those blanks with zeros, suddenly the average tip drops to $1.50. You have literally halved the metric. |
| Sam | And you have to ask, does a blank mean no tip was given? Does it mean the driver forgot to write it down? Or does it mean this specific customer pays by a monthly corporate invoice and tips are handled separately? Wow, yeah, a Python package cannot tell you which of those three human realities is actually true. |
| Alex | So letting pandas skip missing values by default is essentially letting a software developer from 10 years ago make crucial business decisions on your behalf. |
| Sam | It really is an abdication of your responsibility as an analyst. And you know there is another insidious trap with missing data when you try to filter. Let’s say you want to split those farm deliveries into two buckets to see who tips well. You want tips above $2 and tips of $2 or less. |
| Alex | OK, logically, every single delivery has to fall into one of those two buckets, right? The universe of numbers is either greater than 2 or it isn’t. |
| Sam | But if you write that logic in Python, those four rows with blank tips vanish completely. Wait, |
| Alex | really? |
| Sam | Yes. They do not appear in the above 2 bucket, and they do not appear in the less than 2 bucket. In Python, any mathematical comparison you make with a missing NAN value automatically yields false. Oh |
| Alex | wow. So the data just evaporates from your analysis. |
| Sam | It evaporates. And Python will not give you an error message to tell you what happened. |
| Alex | Which makes our next concept the ultimate defense mechanism. Inspect before you conclude. The source material actually insists on 5 specific lines of inspection before you write a single line of computation. And I know the standard move for students is to just print table.head to make sure the CSV loaded, but what are we actually looking for that a simple glance misses? |
| Sam | A simple glance is dangerous because it only shows you the first five rows, which, let’s face it, are usually perfectly clean. These 5 lines of inspection are designed to expose the hidden rot. OK, let’s hear them. First, you run table.shape. This tells you the exact count of rows and columns. If you expected a million rows and you see 10,000, you know the export failed before you even start. |
| Alex | That makes sense. |
| Sam | Second, and this is crucial, table.d types. |
| Alex | This is where a single rogue character ruins an entire weekend. |
| Sam | Yes. Imagine a massive column of revenue numbers. One exhausted data entry clerk accidentally types a dollar sign in row 50,000. D-types will show that Python has silently converted the entire revenue column from numerical data into text strings. |
| Alex | And if you feed that column into a machine learning model, the model will just crash or worse, produce complete garbage. |
| Sam | Exactly. D-Types catches that instantly. |
| Alex | Third is table.head, which we mentioned is your basic sanity check to see the layout. Fourth is table.isol.sum. |
| Sam | Right, that line quantifies the void. It tells you exactly how many blanks exist in every single column. You must always report this number to your stakeholders. Always. And finally, table.describe. This generates the minimums, maximums, and quartiles for your numeric columns. It basically answers the question. Is anything impossible here, |
| Alex | like finding a customer who is -5 years old or a percentage column that somehow maxes out at 800%. |
| Sam | Exactly. Those five lines will literally save your career. But even with that defense, the worst missing values are the ones wearing a disguise. The ones that is null.sum cannot see because they technically aren’t missing. The |
| Alex | disguised blanks like an empty text string with a single space, the actual typed word none or N or unknown, or a zero that doesn’t mathematically mean zero but was just typed by a sensor when it lost power, |
| Sam | or the classic database default date, |
| Alex | January 1st, 1900. |
| Sam | To find those, you must run value counts on your categorical columns. It will expose the misspellings, the disguised placeholders, and the weird outliers that a standard missing value check completely ignores. |
| Alex | You know, the notes detail this brilliant real world use case about a review site with 150,000 business records. The business question is simple Do more expensive restaurants get better star ratings? |
| Sam | Right? And it sounds like a basic one line aggregate function average stars per price level. |
| Alex | But inspecting that data reveals a total minefield. The price level isn’t even a clean column. It’s buried inside a nested dictionary of attributes requiring specialized extraction, and some blanks are stored as the literal string none. It’s a mess. And then you discover that entire states have only 4 businesses listed, meaning a state level average is just statistically meaningless noise. |
| Sam | And the most critical discovery in that example is that restaurants with no listed price level are rated fundamentally differently. From the rest of the data set, |
| Alex | right, if you just drop the rows with missing prices to make your code run cleanly, you have completely skewed the entire comparative analysis. |
| Sam | That example perfectly illustrates why the honest result of a data analysis is almost never a single solitary number. The honest result is a sentence with conditions attached. |
| Alex | Yeah, you don’t just hand a stakeholder the number 4.2, you hand them a sentence. Among restaurants with at least 50 reviews and a verified price level, the average rating rises by x per price tier. Note that 12,000 records had no price data and were excluded, and these excluded restaurants skewed lower in overall ratings. That is infinitely more robust. |
| Sam | It is the difference between a mechanic who just turns a wrench and an engineer who understands the structural integrity of the entire bridge. You know, when you clean data, you must establish a short list of explicit rules |
| Alex | like convert this column to a date. If it fails, force it to be missing or |
| Sam | lowercase all text and strip the white space. And critically, you count what each rule changed and you report those changes. You never silently delete a row of data. |
| Alex | So we started this deep dive talking to you, the graduate student sitting at your screen, looking at a beautifully formatted number. We’ve seen that data analysis isn’t just typing PD.read CSV. It is defining the precise grain of your table, so you aren’t multiplying ghosts. It is shifting your brain away from tedious loops and embracing vectorized columns. It Mastering the purr with split, apply and combine, knowing exactly when to aggregate, transform, or filter based on the shape you need. |
| Sam | And perhaps most importantly, it is relentlessly interrogating blanks and disguises before you trust a single output. |
| Alex | It really entirely reframes what you are studying to do. |
| Sam | It does. And I want to leave you with a final thought to ponder as you progress in your degree. We discussed how panda’s default behavior is to blindly skip missing values, right? And how disguised values like the word unknown or a delivery driver skipping a tip entry will completely invalidate your averages. What this implies is that the most critical skill for a data scientist isn’t actually programming. Python, pandas, NumPy, these are just tools. The real irreplaceable skill is understanding the flawed human behavior and the chaotic, messy business processes that generated that file in the first place. |
| Alex | Yeah, you weren’t just processing data, you are investigating the people and the systems that created it. |
| Sam | Exactly. The next time you sit down to write a perfect line of Python, ask yourself, are you training to be a coder or are you training to be an investigator of human error? Because that crisp, perfectly formatted number on your screen is only as reliable as the messy human reality it represents. |
| Alex | Thank you for joining us on this deep dive. The next time you look at a perfectly formatted number on a screen, remember to ask what it might be hiding. Keep interrogating the data, and we’ll see you next time. |
Presentation
Read
- Python for Data Analysis (lecture notes)
Hands-on
Notebooks in 08-Python-Data-Analysis
Homework
- Homework 7: Invasive Plants, from Raw File to Report — due Wednesday, October 28, 2026