This chapter introduces pandas data frames as the natural way to represent tabular data: each row is a record, each column is one attribute, and each column can have its own data type. It connects this idea to familiar real-world tables such as stock quotes, baggage rules, and nutrition labels, then explains that a data frame is essentially a collection of series sharing a common index. The chapter’s main purpose is to build comfort with the basic operations needed to work with such tables: creating them, inspecting them, selecting subsets, and modifying them.
A major theme is selecting data accurately and efficiently. The text emphasizes the difference between row selection and column selection, especially the fact that square brackets on a data frame refer to columns, while rows are usually accessed with loc or iloc. It shows how to retrieve single rows, multiple rows, single columns, and combinations of rows and columns, including boolean indexing for conditional filtering and the SQL-like query method for more readable expressions. It also explains dot notation for columns, while warning that it can fail with awkward column names and can be confusing when method names overlap with column names.
The exercises use a store inventory and sales example to demonstrate practical data-frame work: creating frames from lists of dicts, dicts of lists, lists of lists, or NumPy arrays; adding new columns with direct assignment or assign; combining frames with concat; filling missing values; and updating cells or subsets of cells with loc. Along the way, the chapter highlights important pandas behaviors such as broadcasting arithmetic across aligned series, the appearance of NaN when data is missing, interpolation for estimating missing values, and the danger of chained indexing that can trigger SettingWithCopyWarning. Overall, it prepares the reader to confidently create, slice, update, and analyze data frames in common analytical tasks.
Table 2.1 as a pandas data frame
Creating a data frame from a list of lists. Each inner list represents one row. Column names are taken positionally.
Creating a data frame from a list of dicts. Each dict is a row, and the keys indicate column values.
Creating a data frame from a dict of lists. Each dict key is a column name, and the list contains values for that column.
Creating a data frame from a two-dimensional NumPy array
Graphical depiction of the solution for exercise 8
Graphical depiction of pd.concat([df, new_products])
Graphical depiction of df.loc[[5,6,7], 'sales'] = [100, 200, 75]
Graphical depiction of df.loc[df['sales'] > df['sales'].mean(), ['product_id', 'name']]
Graphical depiction of creating a data frame via a dictionary
Graphical depiction of interpolate
Summary
In this chapter, we started to work with data frames—creating them, adding data to them, retrieving data from them, analyzing them, and even cleaning up when data is missing. These techniques and those from the previous chapter are the building blocks on which we work with data in pandas. In the next chapter, we’ll tackle more complex scenarios using data from the real world.
FAQ
What is a data frame in pandas?
A data frame is pandas’ table-like data structure for organizing data in rows and columns. Each column is a series, and all columns share a common index.How is a data frame different from a series?
A series is one-dimensional, while a data frame is two-dimensional. In a data frame, each column is its own series, and the frame combines them under one shared index.Why do data frames work well for tabular data?
They match the way tables are naturally organized: each row represents a record, and each column represents one attribute. That makes them easy to read, analyze, and manipulate.How can you create a pandas data frame from a list of dicts?
Pass a list of dictionaries toDataFrame. Each dictionary becomes a row, and the dictionary keys become the column names.How can you create a pandas data frame from a dict of lists?
Pass a dictionary toDataFrame where each key is a column name and each value is a list of column values. Each list must be the same length.What is the difference between loc and iloc?
loc selects by label, while iloc selects by position. Both can be used to retrieve rows from a data frame or elements from a series.Why do square brackets usually refer to columns in a data frame?
In a data frame, square brackets are primarily used to select columns. For row selection, pandas expectsloc or iloc, except in some slicing cases.How do you add a new column to a data frame?
You can assign to a new column name directly, such asdf['new_col'] = .... Another option is to use df.assign(), which returns a new data frame.How do you filter rows using a boolean index?
Create a boolean series from a condition, then use it insideloc or directly with the data frame. For example, df.loc[df['sales'] > df['sales'].mean()] returns rows matching the condition.What does query do in pandas?
query lets you filter rows using a string expression that looks similar to SQL. It is often more readable for complex conditions, but it cannot be used on the left side of an assignment.
Pandas Workout ebook for free