pandas and the DataFrame
Plain Python can do maths, but for analysing tables of data we use a free add-on called a library. A library is a bundle of ready-made tools someone else wrote that you can use. The essential library for data analysis is called pandas, and its central tool is the DataFrame.
The DataFrame: a table you control with code
A DataFrame is simply a table, rows and columns, just like a spreadsheet sheet or a database table, except you manipulate it with code instead of a mouse. This is the same rows-and-columns idea from Module 1, now in Python. To use pandas you first import it (load the library), conventionally giving it the short name pd:
import pandas as pdThat one line makes all of pandas' tools available under the name pd. You do this once at the top of any analysis.
Loading data
Most data arrives as a CSV file (a plain-text table). pandas reads it into a DataFrame in one line:
df = pd.read_csv("sales.csv")\nprint(df.head())Line one: pd.read_csv opens the file "sales.csv" and loads it into a DataFrame, which we store in a variable named df (a common shorthand for "data frame"). Line two: df.head() shows the first few rows, so you can check it loaded correctly. The .head() part is a built-in pandas action you can run on any DataFrame.
Looking at columns
You select a column by naming it in square brackets:
print(df["amount"])This shows just the amount column. And you can instantly summarise it with built-in actions:
print(df["amount"].sum())\nprint(df["amount"].mean())The first prints the total of all amounts; the second prints the average. In two short lines you have done what would take several spreadsheet steps, and you can re-run it on a new file anytime.
- A library is a bundle of ready-made tools; pandas is the one for data.
- Import it once with: import pandas as pd.
- A DataFrame is a table you control with code.
- read_csv loads a file; .sum() and .mean() summarise a column.