This chapter expands on three core pandas skills—grouping, joining, and sorting—by showing how they work in more realistic, multi-step analysis tasks. It emphasizes that the most useful data work often involves combining these techniques: loading several files into one clean data frame, creating useful columns from filenames or other metadata, and then grouping or sorting the result in ways that make patterns easier to see. Along the way, it also introduces related tools such as transposing data, selecting columns, removing duplicates, and using window-style operations.
The first major example builds a single weather data set from multiple city CSV files. The solution reads only the needed columns, extracts city and state names from each filename, standardizes them, and combines all the individual frames with concatenation. Once the data is assembled, grouping by both state and city makes it possible to compare start and end dates across locations, find each city’s lowest recorded minimum temperature, and identify each state’s highest maximum temperature. The exercise reinforces the idea that thoughtful data preparation makes later analysis much simpler and clearer.
The remaining examples deepen the use of grouping, filtering, transforming, and joining. One exercise examines SAT math scores by income bracket across years, using grouping, transposition, and percentage change to compare adjacent income levels and detect consistent differences. Another uses group-based filtering and transformation to analyze city weather and precipitation patterns, keeping only groups that meet conditions and computing each measurement’s share of a city’s total precipitation. The chapter closes with a join-heavy analysis that combines OECD tourism spending with wine ratings, showing how joins on shared indexes can create useful merged views and how correlation can reveal, in this case, only a weak positive relationship between tourism spending and wine quality.
Graphical depiction of using pd.concat to join separate data frames into a single one
Example of using T to transpose a data frame
Get the mean after transposing.
Summary
In this chapter, we dove even further into the world of split-apply-combine, looking at grouping, joining, and sorting from a variety of new perspectives. It’s a rare project that doesn’t use these techniques at least a little, so I hope you took the time to review these exercises and compare your answers with mine.
FAQ
How do you combine multiple CSV files into one DataFrame in this chapter?
You typically loop over the matching filenames, read each CSV into its own DataFrame, store those DataFrames in a list, and then usepd.concat(all_dfs) to create one combined DataFrame.Why does the chapter use glob.glob when loading the weather files?
glob.glob is used to find all filenames matching a pattern, such as ../data/*,*.csv, so you can automatically iterate over every city CSV file instead of listing them one by one.How are city and state extracted from each filename?
The filename is stripped of its prefix and suffix, then split on the comma. That gives two pieces: the city name and the state abbreviation.Why does the code use assign when adding city and state columns?
assign lets you add new columns in a method chain, keeping the loading code concise and readable while returning a new DataFrame.Why group the temperature data by both state and city?
Some city names appear in more than one state, such as Springfield. Grouping by both columns avoids mixing data from different cities with the same name.How do you check whether each city’s data covers the same time period?
Group bystate and city, then find the minimum and maximum date_time values. Comparing those results shows whether the files cover roughly the same date range.How do you find the lowest minimum temperature for each city?
Use a grouped minimum on themin_temp column, such as df.groupby(['state', 'city'])['min_temp'].min().How do you find the highest maximum temperature for each state?
Group bystate and compute the maximum of max_temp, for example df.groupby('state')['max_temp'].max().What is the purpose of transpose or T in the SAT scores exercise?
transpose flips rows and columns. In the SAT exercise, it makes the income brackets behave like rows so that pct_change can compare adjacent income groups.How do filter and transform differ in grouped operations?
filter keeps or rejects whole groups based on a True/False condition, while transform returns a value for each row, modifying the data within each group without removing rows.
Pandas Workout ebook for free