Lesson 01
What Is pandas
Meet pandas, the labelled data library built on NumPy, and its two types: the one-dimensional Series and the two-dimensional DataFrame.
pandas is the Python library for labelled, table-shaped data. It is built on NumPy, so the speed is the same, but every value now carries a label. A Series is one labelled column. A DataFrame is a whole table of them, and it is where most data analysis in Python happens.
Install and import
On your computer, install it once with pip install pandas. In a program, import it as pd. In the playground on this page, pandas loads the first time you run code that imports it, so that first run takes a few seconds.
import pandas as pd
print(pd.__version__)Output (your version may differ):
2.3.3A Series is one labelled column
A Series holds values plus an index of labels. Without an index of your own, the labels are 0, 1, 2, and so on. Printing a Series shows the labels on the left, the values on the right, and the dtype at the bottom.
import pandas as pd
sales = pd.Series([120, 85, 140], index=["Mon", "Tue", "Wed"])
print(sales)
print(sales["Tue"])
print(sales.mean())Output:
Mon 120
Tue 85
Wed 140
dtype: int64
85
115.0A DataFrame is a table of Series
A DataFrame has an index for the rows and a name for each column. Every column is a Series, and they all share the same index. Pull one column out and you get that Series back.
import pandas as pd
team = pd.DataFrame({
"name": ["Avery", "Jordan", "Casey"],
"hours": [42, 31, 55],
"score": [88, 74, 91],
})
print(team)
print(team["score"])
print(type(team["score"]))Output:
name hours score
0 Avery 42 88
1 Jordan 31 74
2 Casey 55 91
0 88
1 74
2 91
Name: score, dtype: int64
<class 'pandas.core.series.Series'>Why pandas and not a list of lists
Columns keep their names, so you never count positions by hand. Whole-column math needs no loop, filtering reads like a sentence, and one call summarizes the numbers.
import pandas as pd
team = pd.DataFrame({
"name": ["Avery", "Jordan", "Casey"],
"hours": [42, 31, 55],
"score": [88, 74, 91],
})
team["per_hour"] = (team["score"] / team["hours"]).round(2)
print(team)
print(team[team["score"] > 80])
print(team["score"].describe())Output:
name hours score per_hour
0 Avery 42 88 2.10
1 Jordan 31 74 2.39
2 Casey 55 91 1.65
name hours score per_hour
0 Avery 42 88 2.10
2 Casey 55 91 1.65
count 3.000000
mean 84.333333
std 9.073772
min 74.000000
25% 81.000000
50% 88.000000
75% 89.500000
max 91.000000
Name: score, dtype: float64Key takeaways
-
pandas is built on NumPy and adds labels
-
A Series is one labelled column. A DataFrame is a table of them
-
Every DataFrame column is a Series that shares the row index
-
Column math, filtering, and summaries need no loop
-
Next: Creating a Series
-
Previous: Saving and Loading Arrays
Loading playground…
Check your understanding
What Is pandas Quiz
What is pandas built on?
1 / 10