Latest / CyberSecurity Summary / Python Data Cleaning Cookbook: Modern techniques and Python tools to detect and remove dirty data and extract key insights
Transcript
- 0:00Speaker 1: Have you ever felt just completely buried in information? You know,
- 0:04Speaker 1: you've got articles, research notes piling up, and you just
- 0:07Speaker 1: want to get to the point. Oh.
- 0:08Speaker 2: Absolutely, it's that feeling of being swamped trying to find
- 0:12Speaker 2: the real gems in well, just a mountain of data.
- 0:15Speaker 1: Exactly, finding those surprising facts, the stuff that really matters,
- 0:19Speaker 1: without wading through everything.
- 0:20Speaker 2: That's tough, it really is, and the sheer volume can
- 0:23Speaker 2: actually hide the insights you're looking for.
- 0:26Speaker 1: Right. Well, that's why today this deep dive is kind
- 0:29Speaker 1: of your shortcut. We want to help you get genuinely
- 0:31Speaker 1: well informed on a topic that honestly is fundamental to
- 0:35Speaker 1: any good analysis, Python data cleaning.
- 0:39Speaker 2: And our guide for this is the Python Data Cleaning
- 0:41Speaker 2: Cookbook by Michael Walker. It came out from Pact Publishing
- 0:44Speaker 2: back in twenty twenty. It's a really comprehensive resource.
- 0:47Speaker 1: It is, so our mission today is basically to pull
- 0:50Speaker 1: out the most important nuggets of knowledge from this cookbook.
- 0:54Speaker 2: Yeah, we want to help you understand the modern techniques,
- 0:57Speaker 2: the Python tools. You need a spot and you know,
- 1:00Speaker 2: fixed dirty data. Think of it like transforming that raw,
- 1:02Speaker 2: messy stuff.
- 1:03Speaker 1: Into something clear, something you can actually.
- 1:05Speaker 2: Use, precisely clear actionable insights. We'll try to surface some
- 1:10Speaker 2: surprising facts too, maybe keep it hopefully entertaining along the way.
- 1:14Speaker 1: Okay, let's jump in then. So data cleaning, the very
- 1:18Speaker 1: first step often is just getting the data into Python,
- 1:22Speaker 1: and that simple step surprisingly can be well tricky, It
- 1:27Speaker 1: really can.
- 1:27Speaker 2: It's fascinating how much variety there is. Right at the start.
- 1:30Speaker 2: You think data is data, but how it's structured or
- 1:34Speaker 2: maybe not structured, sets you up for different challenges right away.
- 1:37Speaker 1: Okay, so let's start with maybe the most common one, CSV.
- 1:40Speaker 2: Files, right, comma separated values basically raw text, comma splitting columns,
- 1:45Speaker 2: new lines for rows, simple concept.
- 1:47Speaker 1: And pandas read. CSV is the tool for that.
- 1:50Speaker 2: It is, But here's the first little catch. Read the
- 1:52Speaker 2: CSV tries to be smart. It makes an educated guess
- 1:55Speaker 2: about your data types.
- 1:56Speaker 1: Oh so it might guess wrong.
- 1:58Speaker 2: It often does, or it might not get exactly what
- 2:00Speaker 2: you need. You usually have to step in, maybe tell
- 2:02Speaker 2: it the column names explicitly, or make sure understands your
- 2:05Speaker 2: dates are actually dates, not just strings of text.
- 2:08Speaker 1: Gotcha, So you need to be specific.
- 2:10Speaker 2: Yeah, take the landtemp's data set for example, It's like
- 2:13Speaker 2: one hundred thousand row sample from this big climate network.
- 2:16Speaker 2: You load it and maybe you run is nullaw.
- 2:19Speaker 1: Dot s okay, and that shows you missing values exactly.
- 2:22Speaker 2: It'll quickly show you, hey, you've got gaps and avtu
- 2:25Speaker 2: temp or maybe the country column. And for something critical
- 2:28Speaker 2: like average temperature. Missing values aren't just counts, they're like
- 2:32Speaker 2: potential analysis killers.
- 2:34Speaker 1: You might drop those rows using DROPNA.
- 2:36Speaker 2: You could yeah, drop the subsetvtemp in lace true would
- 2:40Speaker 2: remove rose missing that crucial temperature. But you know, dropping
- 2:43Speaker 2: isn't always the best move. Sometimes filling those gaps imputation
- 2:47Speaker 2: is better. Depends on the goal.
- 2:48Speaker 1: Right, It's a judgment call.
- 2:49Speaker 2: It is, oh, and a neat little thing about read CSV.
- 2:52Speaker 2: It can often handle zipped CSV files directly saves you
- 2:57Speaker 2: an unzip step handy.
- 2:59Speaker 1: Okay. So ESVs have their quirks. What about Excel files?
- 3:03Speaker 1: I feel like everyone has horror stories about messy spreadsheets.
- 3:06Speaker 2: Oh Excel. Yeah, they bring a whole different set of
- 3:09Speaker 2: let's call them features. We'll use Excel in very flexible ways.
- 3:14Speaker 1: Flexible is a polite word for it.
- 3:16Speaker 2: Huh. Right, So you often find extra rows at the top,
- 3:19Speaker 2: like report titles or maybe summary rows at the bottom,
- 3:23Speaker 2: blank columns used for spacing if it looks fine to
- 3:26Speaker 2: a human but confuses.
- 3:27Speaker 1: The code exactly.
- 3:28Speaker 2: So with Panda's not read Excel, you use arguments like
- 3:31Speaker 2: skip rows, skip footer, use calls to basically tell pandas, okay,
- 3:35Speaker 2: ignore that stuff. Just grab this block of cells you're
- 3:38Speaker 2: targeting the actual data.
- 3:40Speaker 1: Table makes sense, you're zeroing in and.
- 3:42Speaker 2: Another common Excel thing. People use symbols like A or
- 3:46Speaker 2: maybe na to show missing data.
- 3:48Speaker 1: Right, not blank cells, but actual text symbols.
- 3:51Speaker 2: Yeah, Python reads those as texts as object types. So
- 3:54Speaker 2: if you try to do math, it breaks the key move.
- 3:56Speaker 2: Here is pd dot two numeric with the errors.
- 3:58Speaker 1: Coerce argument r's coerce. What does that do?
- 4:01Speaker 2: It tells pandas try to make this column numeric. If
- 4:04Speaker 2: you find anything you can't convert, like wow, just turn
- 4:06Speaker 2: it into nan ah nan.
- 4:08Speaker 1: Not a number Panda's way of saying missing numeric value.
- 4:11Speaker 2: Precisely. Without that step, your numbers are stuck as text.
- 4:15Speaker 2: And oh, watch out for extra spaces too, Like in
- 4:18Speaker 2: that OECD GDP data example. You might have spaces before
- 4:22Speaker 2: or after values. Always use dot str dot strip to
- 4:25Speaker 2: clean those up before you analyze or merge.
- 4:28Speaker 1: So many the little traps. Okay, csvs. EXCEL. What a
- 4:32Speaker 1: pulling data from proper databases like SQL databases, surely that's cleaner.
- 4:36Speaker 2: Generally, Yes, data from enterprise systems SQL databases tends to
- 4:40Speaker 2: be more structured, but the logic isn't always obvious from
- 4:44Speaker 2: the data alone.
- 4:45Speaker 1: What do you mean.
- 4:45Speaker 2: Well, you might find really complex coding schemes like three
- 4:49Speaker 2: means mother has secondary education, or they might use special
- 4:52Speaker 2: numbers like nine nine nine ninet nine to mean missing
- 4:54Speaker 2: or not applicable. It makes sense in the database, but
- 4:57Speaker 2: not when you.
- 4:57Speaker 1: Just pull the raw number right, so the context is
- 4:59Speaker 1: missing exactly.
- 5:00Speaker 2: So you use tools like pimsqual or mysqualapis with pd
- 5:03Speaker 2: dot read school to pull the data, and you can
- 5:06Speaker 2: actually do some initial cleanup in the SQL query itself, like.
- 5:09Speaker 1: Renaming columns or filtering rows right at the source.
- 5:12Speaker 2: Yeah, using the select statement. Then once it's in pandas,
- 5:16Speaker 2: a really good technique is to replace those codes like
- 5:19Speaker 2: three with meaningful labels like secondary ed.
- 5:22Speaker 1: Makes the data much easier to understand totally.
- 5:24Speaker 2: And then this is key for efficiency, convert that column
- 5:28Speaker 2: to a category data type.
- 5:29Speaker 1: Why category?
- 5:30Speaker 2: It saves a ton of memory, especially if you have
- 5:32Speaker 2: text labels repeated many times. The student math data set
- 5:35Speaker 2: example shows this clearly with memory usage index false. It's
- 5:40Speaker 2: not just about clarity, it's about performance.
- 5:42Speaker 1: With bigger data, memory savings are always good. Okay. What
- 5:45Speaker 1: about data from statistical software SPSS data SaaS are.
- 5:50Speaker 2: Yeah, those have their own formats too. Libraries like py
- 5:53Speaker 2: reed stat for SPSS, Stata SaaS and pyritter for our
- 5:56Speaker 2: data files are.
- 5:57Speaker 1: What you'd use and their own querkx I assume.
- 6:00Speaker 2: One thing is these files often have metadata with column
- 6:03Speaker 2: labels that are way more descriptive than the short, sometimes
- 6:06Speaker 2: cryptic variable names.
- 6:08Speaker 1: So you want to use the labels.
- 6:09Speaker 2: Definitely prefer the labels, but then you still need to
- 6:11Speaker 2: clean those up, make them lowercase, replace spaces with underscores,
- 6:15Speaker 2: remove weird characters, make them usable as variable names and python.
- 6:19Speaker 1: Okay, standardizing the names right.
- 6:22Speaker 2: And another big one for stats packages logical missing values. Stata,
- 6:28Speaker 2: for instance, might use codes like meta five point zero,
- 6:30Speaker 2: agive a four point zero and adver meta four one
- 6:32Speaker 2: point zero. These aren't errors, their codes meaning refused, don't know,
- 6:37Speaker 2: not applicable.
- 6:38Speaker 1: Ah. So they look like numbers, but they aren't really
- 6:40Speaker 1: data points.
- 6:40Speaker 2: For analysis exactly you need to tell pandas to treat
- 6:45Speaker 2: those specific numbers as missing, otherwise they'll mess up your
- 6:48Speaker 2: calculations like your averages.
- 6:49Speaker 1: Got it? So much depends on understanding the source of
- 6:52Speaker 1: the data.
- 6:52Speaker 2: Absolutely. Context is everything in cleaning.
- 6:55Speaker 1: Okay, so we've wrangled the data in, we've done some
- 6:57Speaker 1: initial cleanup. Now the book talks about saving this clean
- 6:59Speaker 1: day data. Why is picking the right format important and
- 7:03Speaker 1: what are the trade offs? It seems simple, but maybe
- 7:05Speaker 1: it's not.
- 7:06Speaker 2: That's a really important point. Persisting the data. Why bother
- 7:10Speaker 2: saving it in a new format. Well, maybe you want
- 7:12Speaker 2: to clean snapshot before doing more complex stuff, or the
- 7:16Speaker 2: data doesn't change much so you work off the clean version,
- 7:19Speaker 2: or maybe you want the flexibility of JSON.
- 7:21Speaker 1: Okay, those are good reasons, but what's overlooked.
- 7:25Speaker 2: The trade offs. CSV is memory light, sure, but it's
- 7:29Speaker 2: slow to write for big files, and crucially, it forgets
- 7:32Speaker 2: your data types. All that work converting numbers poof, they
- 7:35Speaker 2: might become strings again when you reload.
- 7:37Speaker 1: Oh that's annoying. What about pickle.
- 7:39Speaker 2: Pickle does remember data types, which is great, but creating
- 7:42Speaker 2: those Pickle files, the serialization process can be heavy on memory,
- 7:45Speaker 2: and CPU might not be ideal on a resource constrained system.
- 7:49Speaker 1: Okay, and feather.
- 7:51Speaker 2: Feather is generally faster and lighter than pickle, and it
- 7:54Speaker 2: plays nice with r which is cool for teams using both,
- 7:57Speaker 2: but you often lose the data frame index, and it's
- 8:00Speaker 2: long term support is maybe less certain than other formats.
- 8:03Speaker 1: So there's no single perfect format.
- 8:05Speaker 2: Not really depends on the needs. But here's the big warning.
- 8:09Speaker 2: When you save data, you separate it from the code
- 8:11Speaker 2: that created it. It's super easy to forget later how
- 8:14Speaker 2: a variable was calculated or cleaned right.
- 8:17Speaker 1: The logic gets lost exactly.
- 8:19Speaker 2: So the advice is only persist your data at significant milestones,
- 8:23Speaker 2: when you've reached a stable, well understood point in your
- 8:27Speaker 2: cleaning process. Treat it like saving a major version.
- 8:30Speaker 1: That makes a lot of sense. Okay, milestone reached data
- 8:34Speaker 1: is imported. What's the very very first thing you do
- 8:36Speaker 1: that question? Everyone asks, so how does it look?
- 8:39Speaker 2: Yeah, that's the immediate next step, and you need a
- 8:41Speaker 2: routine a system. Even if you think you know the data,
- 8:45Speaker 2: a new batch can always.
- 8:46Speaker 1: Have surprises, So a quick diagnostic checkup exactly.
- 8:49Speaker 2: You want to quickly grasp what's the unit of analysis?
- 8:51Speaker 2: How many rows? How many columns, What are the common categories,
- 8:54Speaker 2: how are the numbers distributed? And critically, where are the
- 8:58Speaker 2: missing values and potential outliers. It's about building that initial intuition.
- 9:03Speaker 1: Building intuition. I like that. So what commands give you
- 9:05Speaker 1: that first glance?
- 9:06Speaker 2: Dataframe dot shape for rowsan columns, simple but fundamental dataframe
- 9:11Speaker 2: dot info is gold. It shows data types and counts
- 9:15Speaker 2: non missing values per column, instant red flags for missing data.
- 9:19Speaker 1: Okay, shape and info. What about seeing the actual data?
- 9:22Speaker 2: Dataframe dot head for the first few rows, dataframe dot
- 9:25Speaker 2: tail for the last few, and dataframe dot sample is
- 9:27Speaker 2: great for a random peak. Use sample random state one
- 9:30Speaker 2: if you want the same random sample each time. For reproducibility.
- 9:34Speaker 1: Reproducibility is good always.
- 9:36Speaker 2: And a key tip here set a meaningful index if
- 9:38Speaker 2: you have one, like a unique personad. It makes selecting
- 9:42Speaker 2: specific rows later so much easier. It anchors your data.
- 9:45Speaker 1: Good point. Okay, we've got the overview. How about focusing
- 9:48Speaker 1: on columns, selecting and organizing them.
- 9:50Speaker 2: Standard selection is easy with square brackets or using dot
- 9:53Speaker 2: lock and dot ilock. But a real time saver is
- 9:55Speaker 2: dot filter.
- 9:56Speaker 1: Like how does filter work?
- 9:57Speaker 2: It lets you select columns based on patterns in their
- 9:59Speaker 2: names have columns like weeks work zero one, weeks work
- 10:02Speaker 2: zero one, week's work zero two. You can grab them
- 10:04Speaker 2: all with df dot filter like weeks worked super useful.
- 10:07Speaker 1: Oh nice's typing them all out exactly.
- 10:10Speaker 2: You can also select to buy data type df dot.
- 10:13Speaker 2: Selected types include number gets all numeric columns, or include
- 10:17Speaker 2: category for categoricals and for just keeping things sane. Group
- 10:22Speaker 2: related columns together. Create lists of column names like demographics, age, gender, location, workforce, occupation, income,
- 10:30Speaker 2: and then you can easily work with those logical groups.
- 10:32Speaker 1: Keeps the analysis tidy. Now, what about selecting specific rows?
- 10:36Speaker 1: You mentioned that issues often pop up when you look
- 10:38Speaker 1: at subsets.
- 10:39Speaker 2: Absolutely, this is where booling indexing comes in. You filter
- 10:42Speaker 2: rows based on conditions. For example, and that NLS data
- 10:45Speaker 2: set NLS ninety seven dot nightly hirsleep equal four would
- 10:48Speaker 2: pull out everyone reporting very little.
- 10:50Speaker 1: Sleep, So you can isolate specific groups easily yep.
- 10:53Speaker 2: And you can combine conditions using and for a and
- 10:56Speaker 2: D for or like sleep four and children x three
- 10:59Speaker 2: finds people with little sleep and three or more kids less.
- 11:02Speaker 2: You really zoom in.
- 11:03Speaker 1: You can select rows and columns together.
- 11:05Speaker 2: Yes, using dot lock you can give it row conditions
- 11:07Speaker 2: and column names in one go. Very powerful for getting
- 11:10Speaker 2: exactly the slice of data you need.
- 11:12Speaker 1: Okay, slicing and dicing now, I remember a researcher telling
- 11:15Speaker 1: me once ninety percent of what you'll find is in
- 11:18Speaker 1: the frequency distributions. Why are frequencies so revealing?
- 11:22Speaker 2: Yeah, that's a great quote, and it's often true, especially
- 11:25Speaker 2: for categorical data frequencies. Using series dot value counts are
- 11:29Speaker 2: your best friend. They immediately show you what are the
- 11:32Speaker 2: actual categories present? Are their typos, weird values, too many
- 11:35Speaker 2: other responses?
- 11:37Speaker 1: So it's like a reality check for your categories.
- 11:39Speaker 2: Totally and adding normalized true gives you percentages, which helps
- 11:43Speaker 2: understand the proportions. You can even apply it to multiple
- 11:46Speaker 2: columns at once using dot apply, like checking all those
- 11:49Speaker 2: government responsibility questions in the NLS data together efficient very
- 11:54Speaker 2: and remember that tip about converting text columns object type
- 11:57Speaker 2: to category. It pays off here too, makes these value
- 12:00Speaker 2: counts operations faster and more memory efficient.
- 12:02Speaker 1: Good reminder, Okay, frequencies for categories. What about summarizing our
- 12:06Speaker 1: continuous numeric variables?
- 12:08Speaker 2: Before you analyze numbers, you need to understand their basic properties.
- 12:12Speaker 2: Central tendency like mean or median, spread, standard deviation, and shape, skewness.
- 12:18Speaker 1: And dataframe dot describe is the go to.
- 12:21Speaker 2: For that it is. It gives you count means, standard deviation,
- 12:24Speaker 2: min max, and the quartiles twenty fifth fiftieth which is
- 12:28Speaker 2: the median and seventy fifth percentile. A fantastic quick summary.
- 12:32Speaker 1: It also mentions skewness and critosis. What do those tell us?
- 12:34Speaker 2: Skewness tells you if the distribution is symmetric or locksided.
- 12:38Speaker 2: Critosis tells you about the tails. Are they fat, lots
- 12:41Speaker 2: of extreme values or thin? For instance, in the COVID data,
- 12:46Speaker 2: total cases and total deaths were heavily skewed right, meaning
- 12:50Speaker 2: meaning the mean was much higher than the median. That's
- 12:52Speaker 2: a classic sign of outliers pulling the average up a
- 12:55Speaker 2: few countries with extremely high numbers. It immediately tells you
- 12:58Speaker 2: the simple average might be mislead.
- 13:00Speaker 1: One right, the mean is sensitive to extremes. And how
- 13:04Speaker 1: do we visualize these distributions?
- 13:06Speaker 2: Histograms are the first stop. PLT dots gives you a
- 13:08Speaker 2: quick picture of the shape. Are there multiple peaks? Is
- 13:11Speaker 2: it skewed? Are their values way off on their own?
- 13:14Speaker 1: Okay? And QQ plots. What are they for?
- 13:17Speaker 2: QQ plots usually using stats models dot API dot QQ
- 13:20Speaker 2: plot are more technical. They compare your data's distribution directly
- 13:23Speaker 2: against a theoretical one, usually the normal distribution.
- 13:26Speaker 1: How does that help you?
- 13:27Speaker 2: Plot your data's quantiles against the normal distributions quantiles? If
- 13:31Speaker 2: your data is normally distributed, the points will fall roughly
- 13:34Speaker 2: on a straight diagonal line. Deviations from that line show
- 13:37Speaker 2: you exactly how your data differs from normal. Maybe fatter tails,
- 13:41Speaker 2: maybe skewness. It's a great diagnostic got it?
- 13:44Speaker 1: And detecting outliers that one point five times IQR rule.
- 13:47Speaker 2: Yeah, that's a common rule of thumb. Calculate the intercartile
- 13:50Speaker 2: range IQR, which is the distance between the seventy fifth
- 13:53Speaker 2: and twenty fifth percentiles. Anything below q one one point
- 13:57Speaker 2: five iqr or above q three plus one point five
- 14:01Speaker 2: iqr is flagged as a potential outlier.
- 14:03Speaker 1: Potential outlier, so not definitely wrong, but worth investigating exactly.
- 14:07Speaker 2: A good practice is to output these potential outliers, maybe
- 14:11Speaker 2: save them to a separate Excel file along with some
- 14:13Speaker 2: related data, so you can examine them more closely. Are
- 14:16Speaker 2: they data errors or are they genuinely unusual but valid cases.
- 14:20Speaker 1: Right, context matters again. Okay, we've got the basic checks done.
- 14:22Speaker 1: But data isn't just about individual variables, It's about relationships.
- 14:26Speaker 1: How do we start digging into those?
- 14:27Speaker 2: This is where it gets really interesting because sometimes issues,
- 14:31Speaker 2: especially outliers, only really jump out when you look at
- 14:33Speaker 2: two or more variables together.
- 14:35Speaker 1: Like your example, a ten year old earning fifty million dollars.
- 14:38Speaker 1: Each number might be okay on its own, but.
- 14:40Speaker 2: Together exactly that combination flags a huge issue. So how
- 14:44Speaker 2: do we spot these? One way is using cross tabulations,
- 14:48Speaker 2: but smartly, you can use pd dot q cut to
- 14:51Speaker 2: bin your continuous variables into quantiles, say very low to
- 14:55Speaker 2: very high based on ranges.
- 14:57Speaker 1: Okay, so you categorize the continuous data right.
- 15:00Speaker 2: Then you use pd dot cross stab to see how
- 15:02Speaker 2: the quantiles of two variables relate. In the COVID data. Example,
- 15:06Speaker 2: you could cross tab total case ESKIC and total deaths GIT.
- 15:10Speaker 2: That might show you countries like Qatar and Singapore in
- 15:12Speaker 2: the very high cases bin, but only the medium death spin.
- 15:16Speaker 2: That discrepancy jumps right out.
- 15:17Speaker 1: A pattern that doesn't fit the general tread.
- 15:19Speaker 2: Precisely and visually. Scatterplots are key seaborne dot reg plot
- 15:23Speaker 2: is great because it shows the points and fits a
- 15:25Speaker 2: regression line. You can immediately see points that fall far
- 15:27Speaker 2: from the line potential by variate outliers.
- 15:30Speaker 1: What about identifying points that have a really big influence
- 15:32Speaker 1: on that regression line.
- 15:34Speaker 2: Ugh, that's where statistical measures like Cook's distance come in.
- 15:37Speaker 2: It basically measures how much the entire regression model changes
- 15:41Speaker 2: if you remove a single specific data point.
- 15:43Speaker 1: So a high Cook's distance means that point is really polling.
- 15:46Speaker 2: The line exactly. It has high leverage or influence. Removing
- 15:50Speaker 2: an outlier like Qatar and the COVID analysis, for instance,
- 15:53Speaker 2: could significantly change the calculated relationship between say median age
- 15:58Speaker 2: and cases per million. It tells you that single point
- 16:01Speaker 2: is heavily impacting your conclusion.
- 16:03Speaker 1: That's powerful. What if we suspect outliers based on many
- 16:06Speaker 1: variables at once, not just two?
- 16:08Speaker 2: For that multivariate perspective, Canearest Neighbors kNN is a good approach,
- 16:13Speaker 2: often using the piod library Pieto. Yeah, it's a Pipelon
- 16:16Speaker 2: library specifically for outlier detection. It wraps algorithms like kNN
- 16:20Speaker 2: from Psychic Learn. The idea with kNN is to find
- 16:23Speaker 2: points that are far away from their neighbors in multidimensional space.
- 16:27Speaker 1: So points that don't fit in with any cluster.
- 16:29Speaker 2: Kind of yeah, but remember, for distance based methods like kNN,
- 16:33Speaker 2: you must standardize your data first, usually using Z scores,
- 16:38Speaker 2: Otherwise variables with larger ranges will dominate the distance calculation.
- 16:42Speaker 1: Right, put everything on the same scale exactly.
- 16:44Speaker 2: Applying this to the COVID data might flag Singapore, Qatar,
- 16:48Speaker 2: Hong Kong as outliers when considering both cases and deaths
- 16:51Speaker 2: per million together, revealing multifaceted anomalies.
- 16:55Speaker 1: Okay, outlier detection covered. Now let's get into the real
- 16:58Speaker 1: workhorse stuff, manipulating the data itself.
- 17:01Speaker 2: Series operations right pandas series. Think of them as the
- 17:04Speaker 2: columns in your data frame are where most columnwise action happens.
- 17:08Speaker 2: Basic access uses slicing like misoriestart five or dot lock
- 17:12Speaker 2: for label based access, dot ilock for position.
- 17:15Speaker 1: Based standard indexing. What about changing values based on.
- 17:18Speaker 2: Conditions numbe where is incredibly useful for that basic if
- 17:22Speaker 2: then else logic on a column np dot ware condition
- 17:24Speaker 2: value of true value false, like assigning high or low
- 17:27Speaker 2: elevation based on a threshold, simple and fast.
- 17:30Speaker 1: But what If the logic is really complicated involving multiple
- 17:33Speaker 1: columns for each row, that's where.
- 17:34Speaker 2: You often need apply access one with a custom function.
- 17:38Speaker 2: A UDF user defined function, you write a function that
- 17:41Speaker 2: takes a row of data as input, applies your complex
- 17:44Speaker 2: logic using values from different columns in that row, and
- 17:47Speaker 2: returns a result for that row, like.
- 17:49Speaker 1: The sleep deprived reasons example, checking kids wages, work hours
- 17:53Speaker 1: for each person exactly.
- 17:55Speaker 2: Apply access one lets you handle that row by row
- 17:58Speaker 2: custom logic, which is sometimes unavoidable for really specific business
- 18:02Speaker 2: rules or derived variables.
- 18:04Speaker 1: Okay, and text data string cleaning must be common.
- 18:07Speaker 2: Oh yeah, huge part of cleaning pandas dot dr accessor
- 18:11Speaker 2: is your friend here. Sdr dot contains to find substrings,
- 18:14Speaker 2: str dot strip to remove leading trailing white space, str
- 18:18Speaker 2: dot lower or straw dot upper for case changes, cdr
- 18:21Speaker 2: dot replace for substitutions.
- 18:22Speaker 1: What about more complex patterns, That's.
- 18:24Speaker 2: Where regular expressions come in use with methods like str
- 18:27Speaker 2: dot sindel or Steward dot extract. If you need to
- 18:30Speaker 2: pull out specific patterns like codes or numbers embedded in
- 18:33Speaker 2: text rejects is the way to go. Cleaning up something
- 18:35Speaker 2: like marital status, where you might have married with a
- 18:37Speaker 2: trailing space is a classic dr dot strip job.
- 18:40Speaker 1: Dates too, calculations like age.
- 18:42Speaker 2: Definitely first step is always converting date columns to proper
- 18:46Speaker 2: DateTime objects using cordid dot to date time. Once they
- 18:50Speaker 2: are date times, you can easily film missing dates fil serena,
- 18:53Speaker 2: calculate time differences like subtracting birth date from today's date
- 18:57Speaker 2: to get age, or find intervals like days since a specific.
- 18:59Speaker 1: Of and filling missing values. Imputation we mentioned dropping or
- 19:04Speaker 1: using a simple fill. You're smarter ways.
- 19:06Speaker 2: Beyond fill and NONA. With a constant. You can impute
- 19:09Speaker 2: with the overall mean or median. Better yet, use a
- 19:12Speaker 2: group mean with group b transform means.
- 19:15Speaker 1: How does transform works there?
- 19:17Speaker 2: It calculates the mean for each group, say the mean
- 19:20Speaker 2: income for each occupation, and then broadcasts that group specific
- 19:23Speaker 2: mean back to fill the missing values within that group,
- 19:26Speaker 2: more targeted than a global memet. You can also use
- 19:30Speaker 2: ephyl forward fill or b phil backward fill to propagate
- 19:33Speaker 2: the last or next known value. And for a machine
- 19:36Speaker 2: learning approach, there's kN a imputer from Psychic Learn.
- 19:39Speaker 1: Using kN N again.
- 19:40Speaker 2: Yeah, kN imputer finds the k most similar ros based
- 19:44Speaker 2: on the other columns and uses their values to estimate
- 19:47Speaker 2: the missing value. It leverages the relationships in your data.
- 19:51Speaker 2: Can be very effective, but computationally more expensive.
- 19:54Speaker 1: Lots of options for missing data, Okay, shifting gears a bit.
- 19:58Speaker 1: Analysts spend tons of time on and what Hadley Wickham
- 20:01Speaker 1: famously called split, apply, combine. Could you unpack that?
- 20:05Speaker 2: It's a fundamental pattern in data analysis. You split your
- 20:09Speaker 2: data into groups based on some criteria. You apply some
- 20:13Speaker 2: function like calculate a means some count to each group independently,
- 20:17Speaker 2: and then you combine the results back into a useful summary.
- 20:20Speaker 1: Structure and pannas. Group B is the main tool for this.
- 20:22Speaker 2: Absolutely. While you could technically loop through your data, maybe
- 20:26Speaker 2: using inner tuples or NumPy raise for speed, group B
- 20:29Speaker 2: is almost always vastly more efficient and concise.
- 20:32Speaker 1: So how does group be work.
- 20:33Speaker 2: You call dfsf dot group B column to group B.
- 20:37Speaker 2: This creates a special group B object. Then you chain
- 20:40Speaker 2: an aggregation method like dot mean or dot described to
- 20:43Speaker 2: calculate results for each group.
- 20:45Speaker 1: Can you do multiple calculations at once?
- 20:47Speaker 2: Yes? Using dot ag this is super flexible. You can
- 20:50Speaker 2: pass it a list of functions mean std to apply
- 20:54Speaker 2: to all columns, or a dictionary to apply different functions
- 20:57Speaker 2: to different columns like col a some coal mean.
- 21:00Speaker 1: So you can get complex summaries easily, and this changes
- 21:03Speaker 1: the unit of analysis often.
- 21:05Speaker 2: Yes, if you group daily sales by month and calculate
- 21:08Speaker 2: the sum, your result is now monthly sales. You've aggregated
- 21:13Speaker 2: the output. Might need that reset index to turn the
- 21:15Speaker 2: group keys back into columns or unstack to reshape it.
- 21:19Speaker 2: It's how you roll up data.
- 21:20Speaker 1: Very powerful. Okay, what about sticking data sets together vertically first?
- 21:25Speaker 2: Using concat is for stacking data frames on top of
- 21:28Speaker 2: each other appending rows. Think adding this month's data to
- 21:32Speaker 2: last months, or combining data from different regions that have
- 21:34Speaker 2: the same columns.
- 21:35Speaker 1: What's the main thing to watch out for?
- 21:37Speaker 2: Column names and data types. If the columns aren't exactly
- 21:40Speaker 2: the same or the types differ, concat can get confused
- 21:43Speaker 2: or produce weird results, like turning numbers into generic object types.
- 21:47Speaker 2: Always check alignment before concatenating.
- 21:49Speaker 1: Good heads up. Now the trickier one horizontal combination merge
- 21:56Speaker 1: you mentioned. This is where accidents happen.
- 21:58Speaker 2: Hah. Yes, merging or jaining tables is fundamental, but it's
- 22:02Speaker 2: so easy to get wrong, especially with different join types.
- 22:05Speaker 2: I often joke you need a buddy to double check
- 22:07Speaker 2: your merges.
- 22:08Speaker 1: Okay, so one to one merges are easy, unique keys
- 22:11Speaker 1: in both tables, and multiple keys are possible too. Where
- 22:15Speaker 1: does the danger zone start?
- 22:17Speaker 2: It starts with one too many merges. One table has
- 22:20Speaker 2: unique keys like customer ID in a customer table. The
- 22:23Speaker 2: other has duplicates, like the same customer ID appearing multiple
- 22:26Speaker 2: times in an order's table.
- 22:28Speaker 1: Right, and the key here is inner versus left join
- 22:31Speaker 1: critical difference.
- 22:33Speaker 2: An inner join only keeps rows where the key exists
- 22:36Speaker 2: in both tables. If a customer hasn't placed an order,
- 22:38Speaker 2: they disappear. A left join keeps all rows from the
- 22:40Speaker 2: left table customers and brings in matching data from the
- 22:43Speaker 2: right orders. Customers with no orders will still be there,
- 22:46Speaker 2: but order details will be nan. Choosing the wrong join
- 22:50Speaker 2: type can silently drop data you needed.
- 22:52Speaker 1: That sounds like a very easy mistake to make, it is.
- 22:55Speaker 2: And then there's the dreaded many to many merge keys
- 22:57Speaker 2: are duplicated in both tables.
- 22:59Speaker 1: The book said this should rarely.
- 23:02Speaker 2: Be needed because it usually means something is wrong. Conceptually,
- 23:05Speaker 2: a direct many to many merge creates a Cartesian product,
- 23:09Speaker 2: every matching row on the left joins with every matching
- 23:12Speaker 2: row on the right. If you merge students and courses
- 23:15Speaker 2: where both have duplicate IDs, you can end up matching
- 23:17Speaker 2: every student to every course multiple times, inflating counts and
- 23:20Speaker 2: some nonsensically.
- 23:22Speaker 1: So what's the fix?
- 23:23Speaker 2: Usually you need to rethink your data structure before the merge,
- 23:26Speaker 2: find or create a unique identifier for the relationship you
- 23:29Speaker 2: actually want to capture, recover the implied one to many
- 23:33Speaker 2: link first, rather than doing a raw many to many.
- 23:36Speaker 1: Okay, avoid many to many if possible. What about just
- 23:39Speaker 1: tidying up duplicates within a table?
- 23:41Speaker 2: Drop duplicates is your friend. There. You can specify subset
- 23:44Speaker 2: to check for duplicates based only on certain columns, and
- 23:47Speaker 2: keep lets you choose whether to keep the first or
- 23:50Speaker 2: last duplicate encountered. Like drop duplicates subset location, keep last
- 23:54Speaker 2: to get just the latest COVID data row for each country.
- 23:58Speaker 1: And this relates back to that data idea.
- 24:01Speaker 2: Absolutely, fixing many to many often involves making your data tidier.
- 24:05Speaker 2: Instead of one giant MESSI table, break it down into
- 24:08Speaker 2: smaller related tables where each piece of information lives in
- 24:11Speaker 2: only one place a table for museum items, another for creators,
- 24:15Speaker 2: another for citations, all linked by IDs, cleaner, less error prone.
- 24:20Speaker 1: Makes sense? Okay. Sometimes we need to reshape data moving
- 24:24Speaker 1: between wide and long formats. Why do we do that?
- 24:27Speaker 2: Often analytical tools or models prefer data in a long format,
- 24:31Speaker 2: where you have one Rowe observation per time point or category,
- 24:34Speaker 2: rather than having time points or categories spread across columns
- 24:38Speaker 2: wide format.
- 24:38Speaker 1: So how do we go from winde to long?
- 24:40Speaker 2: Stack is a basic way. It pivots columns into the index.
- 24:43Speaker 2: More flexible is MELT. You tell it which columns are identifiers,
- 24:47Speaker 2: idvars and which columns you want melt down value VARs.
- 24:50Speaker 2: You can name the new variable and value columns too.
- 24:52Speaker 1: Like turning week's work zero week's work zero one into
- 24:55Speaker 1: a single year column and a single value column exactly.
- 24:58Speaker 2: MELT is great for that you you have multiple sets
- 25:01Speaker 2: of columns following a pattern like weeks worked by year
- 25:05Speaker 2: and deep Poliner college enrollment by year. Then pd dot
- 25:08Speaker 2: wide to long is often more powerful. It's designed to
- 25:12Speaker 2: handle those structured wide formats efficiently, reshaping multiple variable groups
- 25:16Speaker 2: simultaneously based on naming conventions.
- 25:19Speaker 1: Very cool, and the reverse long back to.
- 25:21Speaker 2: Wide that uses unstack or pivotable. Sometimes you need data
- 25:26Speaker 2: in a wide format for reporting or for software that
- 25:28Speaker 2: expects it that way, even if it's technically untidy.
- 25:31Speaker 1: Okay, fantastic overview of the core manipulation tools. When doing
- 25:35Speaker 1: all this manually every time new data arrives sounds exhausting.
- 25:39Speaker 1: How do we automate? Right?
- 25:41Speaker 2: That's the ultimate goal, isn't it making the cleaning process
- 25:43Speaker 2: repeatable and reliable. This is where reusable code, functions and
- 25:46Speaker 2: classes becomes essential. It separates the logic of your cleaning
- 25:50Speaker 2: from the specific data set you're working on at that moment.
- 25:52Speaker 1: So user defined functions UDS or a big part of this,
- 25:55Speaker 1: building our own little toolkit exactly.
- 25:57Speaker 2: You can create functions for common tasks like at first
- 26:00Speaker 2: look function in a separate Python file Basic Descriptives dot
- 26:03Speaker 2: py that you import, run it on any new data frame,
- 26:06Speaker 2: and it instantly gives you the shape info head unique
- 26:10Speaker 2: ideas your standard first.
- 26:11Speaker 1: Checks automating the diagnostics.
- 26:13Speaker 2: YEP, or functions like get tots to calculate custom stats,
- 26:17Speaker 2: maybe including specific percentiles like fifteenth and eighty fifth, or
- 26:21Speaker 2: get missings to summarize missing data cleanly by row and column,
- 26:25Speaker 2: maybe as percentages.
- 26:26Speaker 1: And for visualization or outliers.
- 26:28Speaker 2: You could have a get disprops function that returns skew
- 26:31Speaker 2: crtosis maybe runs a normality test on a column, or
- 26:35Speaker 2: a make plot function that wraps map plot lib or
- 26:37Speaker 2: seaborn to quickly generate standard histograms or box plots without
- 26:42Speaker 2: rewriting the plotting code every time, so.
- 26:44Speaker 1: You build up a library of your common cleaning steps precisely.
- 26:48Speaker 2: You could even have more complex functions like that AJA
- 26:51Speaker 2: means example, for calculating running totals, but with logic to
- 26:53Speaker 2: exclude sudden huge jumps, like maybe in daily COVID case
- 26:57Speaker 2: reporting using numbpier rays internal for efficiency.
- 27:00Speaker 1: Okay, functions are great for reasonable steps. What about classes?
- 27:03Speaker 1: How do they fit into data cleaning automation.
- 27:06Speaker 2: Classes offer a different way to structure your logic, especially
- 27:08Speaker 2: when you think about the unit of analysis. You could
- 27:11Speaker 2: define a respondent class for the NLS.
- 27:13Speaker 1: Data, so each object of the class represents one person exactly.
- 27:17Speaker 2: You'd initialize it with a row of data, maybe as
- 27:20Speaker 2: a dictionary. Then you can define methods on that class
- 27:23Speaker 2: to calculate things specific to that respondent, like a child
- 27:26Speaker 2: NHUMB method or abwixworked or age b date. The logic
- 27:30Speaker 2: related to a respondent lives with the respondent's data inside
- 27:34Speaker 2: the object.
- 27:34Speaker 1: That sounds quite intuitive. Where do classes really become powerful? Though?
- 27:38Speaker 2: They truly shine with complex non tabular data like nested
- 27:42Speaker 2: JASON or XML. Think about that museum data example. One
- 27:47Speaker 2: JSON record for an artwork might contain a list of creators,
- 27:50Speaker 2: each with their own details and a list of citations.
- 27:52Speaker 1: Right, nested structures hard to flatten cleanly.
- 27:55Speaker 2: Very but with a collection item class you could have
- 27:57Speaker 2: methods like birth your Creator one that direct accesses the
- 28:00Speaker 2: first creator's birth year within the nested structure, or birth
- 28:04Speaker 2: your Soul that loops through the creator's list inside the
- 28:06Speaker 2: object and returns all their birth years.
- 28:08Speaker 1: So you're working with the data's natural hierarchy instead of
- 28:11Speaker 1: forcing it flat exactly.
- 28:13Speaker 2: It avoids many of the errors that come from complex
- 28:15Speaker 2: flattening and merging. You model the data conceptually. Now, iterating
- 28:19Speaker 2: and creating class instances can use more memory and time
- 28:23Speaker 2: than pure vectorized pandas for simple tasks.
- 28:26Speaker 1: But the tradeoff is clarity and correctness for complex data.
- 28:30Speaker 2: Often yes, the conceptual clarity, the intuitive modeling, and potentially
- 28:34Speaker 2: fewer passes over the raw data can make it a
- 28:37Speaker 2: winner for intricate cleaning tasks, especially with nested or irregular
- 28:41Speaker 2: data structures. It helps you focus on the meaning of
- 28:44Speaker 2: the data unit.
- 28:45Speaker 1: Wow, that's quite a comprehensive journey we've been on from
- 28:48Speaker 1: just getting data in wrestling with formats, doing those initial checks,
- 28:52Speaker 1: spotting outliers, reshaping, all the way to building automated functions
- 28:57Speaker 1: and glasses.
- 28:57Speaker 2: It really covers the spectrum, and the key takeaway I
- 29:00Speaker 2: think isn't just the specific Python commands, but developing that
- 29:03Speaker 2: critical eye for data quality, building confidence that the information
- 29:07Speaker 2: you're using is sound.
- 29:08Speaker 1: It feels like this is the shortcut to actually using
- 29:11Speaker 1: information effectively, getting real meaning out of the noise.
- 29:14Speaker 2: It truly is clean. Data is the foundation for any
- 29:17Speaker 2: reliable insight.
- 29:18Speaker 1: So maybe a final thought for every listening as you
- 29:21Speaker 1: look at your own data, consider this, if knowledge really
- 29:25Speaker 1: is most valuable when it's understood and applied, What patterns,
- 29:29Speaker 1: what crucial insights might still be hidden in your data sets,
- 29:32Speaker 1: just waiting for the right cleaning technique to reveal them.
- 29:35Speaker 2: That's a great question. We really encourage you to explore
- 29:38Speaker 2: these libraries PANDAS, NUMPI piod stats models. Experiment with these techniques.
- 29:44Speaker 2: See the power of clean data for yourself.
- 29:46Speaker 1: Absolutely the path to being well informed to getting real insights.
- 29:50Speaker 1: It's an ongoing process, and solid data cleaning is always
- 29:53Speaker 1: that essential first step.