This chapter introduces the core pandas workflow of split-apply-combine, showing how data analysis often requires breaking a data set into meaningful subsets, combining separate sources, transforming values, and ordering results. It emphasizes that these operations are central to practical data work and closely resemble familiar SQL ideas, especially grouping and joining. The chapter also highlights sorting as a flexible way to inspect and rank rows by one or more columns.
The examples first focus on sorting taxi trip data to answer questions about the 20 longest rides and the effect of different sort directions, while also pointing out small floating-point differences that can appear in computed averages. From there, the text explains how to sort by multiple columns with different ascending and descending settings, and how to create categorical groupings for later analysis. Along the way, it reinforces practical pandas habits such as using method chaining, selecting only needed columns, and understanding when to use index-based selection versus positional selection.
The grouping and joining sections then show how to summarize data by categories such as passenger count, department, trip length, and country, using aggregation methods like mean, count, std, sum, and multiple aggregations at once. The chapter explains how grouping returns concise summary results, why it is more efficient than looping over rows, and how to control group-key sorting when needed. Finally, it demonstrates joining normalized data frames on shared keys, combining product and sales tables as well as tourism and country-name tables, to produce richer reports that are easier to read and analyze.
Running sort_values on a data frame returns a new data frame with the same rows but ordered according to the named column.
Running sort_values on a data frame, keeping only one column
Running sort_values on a data frame, then keeping only one column, and then getting only the first rows with iloc
Sorting a data frame by passenger_count (ascending order) and then trip_distance (descending order)
Graphical depiction of how groupby and then mean work together
Graphical depiction of how you can run sort_values on the groupby result
Graphical depiction of making the LOCATION column the index of tourism_df
Graphical depiction of making the LOCATION column the index of locations_df
Graphical depiction of joining locations_df and tourism_df. Notice that any rows referring to a country not in locations_df are dropped from the result.
Summary
Once you’ve read data into a data frame, there are many ways in which you can split, combine, and analyze it. In this chapter, we looked at some of the most common tasks—from grouping for analysis, to grouping for including/excluding rows, to joining and merging data frames. Having these skills at your fingertips makes it easy to perform particularly complex types of analysis. The exercises in this chapter showed you how and when you can use these tools to explore your data in ways that analysts perform on a regular basis, with the “split-apply-combine” approach that’s pervasive in pandas. In the next chapter, we’ll build on what we’ve done here, using these techniques in more advanced ways.
FAQ
What is the main idea behind “split-apply-combine” in pandas?
It means breaking data into groups, applying a function or calculation to each group, and then combining the results into a useful output.When should you use groupby in pandas?
Use groupby when you want to calculate something separately for each category or subset of your data, such as averages by department, totals by year, or counts by passenger number.How is groupby similar to SQL GROUP BY?
Both let you organize rows into groups based on one or more columns and then run aggregate calculations like mean, sum, or count on each group.What is the difference between sort_index() and sort_values()?
sort_index() sorts rows by index values, while sort_values() sorts rows based on the values in one or more columns.Why do you often use iloc after sorting a data frame?
After sorting, the index may no longer be in numeric order. iloc selects rows by position, so it is a reliable way to get the first or last rows after sorting.What is the difference between join and merge?
join combines data frames based on their indexes, while merge combines data frames based on one or more columns.Why is joining data frames useful?
Joining lets you keep related data in separate, smaller tables and combine them only when needed, which is a common normalization strategy in data analysis.How do you apply multiple aggregations to a grouped data set?
You can useagg with a list of aggregation names, such as ['mean', 'std'], to compute several statistics for each group.How can you group by one column and aggregate a different column?
Use syntax likedf.groupby('department')['retail_price'].mean(), where one column defines the groups and another column provides the values to aggregate.How do you create categories from numeric data for grouping?
Usepd.cut to turn a numeric column into bins or categories, such as short, medium, and long, and then group by that new categorical column.
Pandas Workout ebook for free