pandas Series and DataFrames: Your First Table, Inspected and Sorted
A Series is one labelled column; a DataFrame is columns sharing an index. Build both, inspect them with info and describe, select and add columns, sort rows, and see copy-on-write in pandas 3.
What you will learn
- Create a Series and a DataFrame and explain how they fit together
- Inspect a table with shape, dtypes, head, tail, info and describe
- Select columns, add a column with a rule, and compute sums and means
- Sort rows with sort_values and understand copy-on-write in current pandas
Before you start
- Python lists and dictionaries
- NumPy arrays and dtypes
NumPy gave you fast numbers, but those numbers had no names on them. pandas adds the names, so every value sits under a column and beside a row label. That's why people reach for it whenever data looks like a table.
Think of a spreadsheet. Take one column of scores: each value has a row label beside it, and pandas calls that a Series. Now slide a few more columns next to it, all lined up on the same row labels. That's a DataFrame: columns sharing an index. The index is just pandas' word for the row labels.
You install the library once with pip install pandas and import it as pd. Outputs below are from pandas 3.1.1.
Your first Series
import pandas as pd
s1 = pd.Series([10, 20, 30])
print(s1)
print(type(s1))
0 10
1 20
2 30
dtype: int64
<class 'pandas.Series'>
You didn't give labels, so pandas numbers the rows itself: 0, 1, 2. dtype is the type of the values, here whole numbers. It's more than a list: it's a column that knows its labels.
s2 = pd.Series({"a": 100, "b": 200, "c": 300})
print(s2)
print(s2.index.to_list())
print(s2.values)
print(s2.dtype)
print(s2["b"])
a 100
b 200
c 300
dtype: int64
['a', 'b', 'c']
[100 200 300]
int64
200
Pass a dictionary and the keys become the labels. .values prints with no commas because it's a NumPy array underneath. And you look a value up by its label, just like a dictionary.
Your first DataFrame
import pandas as pd
data = {
"name": ["Alice", "Bob", "Charlie"],
"age": [25, 30, 35],
"score": [85, 92, 78],
}
df = pd.DataFrame(data)
print(df)
print(df.shape)
print(df.columns.to_list())
print(df.index.to_list())
name age score
0 Alice 25 85
1 Bob 30 92
2 Charlie 35 78
(3, 3)
['name', 'age', 'score']
[0, 1, 2]
Each key is a column name and each list is that column's values. The three lists stand up as three columns on one shared index, so row 1 means Bob, 30 and 92 together. shape is rows then columns, with no brackets after it, because it's a stored value, not a method.
Pull one column out with df["score"] and you get a Series that keeps the labels and carries the column's name:
0 85
1 92
2 78
Name: score, dtype: int64
So everything you learned about a Series works on any column.
Each column has a type
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie"],
"age": [25, 30, 35],
"score": [85.5, 92.0, 78.25],
})
print(df.dtypes)
print(df["name"].dtype)
print(df["age"].dtype)
name str
age int64
score float64
dtype: object
str
int64
str is how current pandas marks a text column. Older tutorials show object there, so don't let that throw you. The dtype: object on the last line of the first print is something else: df.dtypes is itself a Series whose values are types, and that line describes the printout, not your columns. dtypes with an s is for the whole table, dtype is for one column.
A first look at any table
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie", "Diana", "Evan"],
"age": [25, 30, 35, 28, 41],
"score": [85, 92, 78, 88, 95],
})
print(df.head(2))
print(df.tail(2))
df.info()
name age score
0 Alice 25 85
1 Bob 30 92
name age score
3 Diana 28 88
4 Evan 41 95
<class 'pandas.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 name 5 non-null str
1 age 5 non-null int64
2 score 5 non-null int64
dtypes: int64(2), str(1)
memory usage: 252.0 bytes
head and tail show a sample (five rows if you leave the number out), and the rows keep their labels. info() prints by itself, so there's no print around it. It gives the size, then one line per column with its count of filled cells and its type. Run it first on any new table.
describe in one line
On the three-row Alice, Bob, Charlie table:
print(df.describe())
age score
count 3.0 3.0
mean 30.0 85.0
std 5.0 7.0
min 25.0 78.0
25% 27.5 81.5
50% 30.0 85.0
75% 32.5 88.5
max 35.0 92.0
Only the number columns appear; name is text, so it's left out. std says how far values sit from the mean. The percent rows are cut points: 50% is the middle value, and 25% is a quarter of the way up. One line gives you a feel for every number column.
Selecting columns, and two small traps
print(df["name"])
print(df.name)
print(df[["name", "score"]])
0 Alice
1 Bob
2 Charlie
Name: name, dtype: str
0 Alice
1 Bob
2 Charlie
Name: name, dtype: str
name score
0 Alice 85
1 Bob 92
2 Charlie 78
One name gives a Series. A list of names (note the double brackets) gives a smaller DataFrame.
Ask for a column that doesn't exist, like df["salary"], and pandas raises KeyError: 'salary'. Check your spelling against df.columns. The second trap is a column whose name clashes with a method:
df = pd.DataFrame({
"name": ["Alice", "Bob"],
"count": [3, 4],
})
print(df["count"])
print(df.count)
0 3
1 4
Name: count, dtype: int64
<bound method DataFrame.count of name count
0 Alice 3
1 Bob 4>
A DataFrame already has a count method, and the method wins. The dot is handy for quick work, but square brackets always mean a column.
Adding a column, sums and means
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie"],
"score": [85, 92, 78],
})
df["passed"] = df["score"] > 80
df["bonus"] = df["score"] + 5
print(df)
print(df.columns.to_list())
name score passed bonus
0 Alice 85 True 90
1 Bob 92 True 97
2 Charlie 78 False 83
['name', 'score', 'passed', 'bonus']
Adding a column is just an assignment. You write the rule once, and pandas runs it down the whole column with no loop. To remove one, df.drop(columns="bonus") gives you a table without it.
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie"],
"age": [25, 30, 35],
"score": [85, 92, 78],
})
print(df["score"].sum())
print(df["score"].mean())
print(df["score"].max())
print(df[["age", "score"]].mean())
255
85.0
92
age 30.0
score 85.0
dtype: float64
Select first, then calculate. On several columns, mean works column by column and returns a Series labelled by column name.
Sorting rows
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie"],
"score": [85, 92, 78],
})
print(df.sort_values("score"))
print(df.sort_values("score", ascending=False))
print(df)
name score
2 Charlie 78
0 Alice 85
1 Bob 92
name score
1 Bob 92
0 Alice 85
2 Charlie 78
name score
0 Alice 85
1 Bob 92
2 Charlie 78
Look at the labels: 2, 0, 1. They travel with their rows, so each row stays whole. And df itself is still in the old order. sort_values gives you a new table; assign it to a variable if you want to keep it.
Copy-on-write
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie"],
"score": [85, 92, 78],
})
scores = df["score"]
scores[0] = 0
print(scores.to_list())
print(df["score"].to_list())
[0, 92, 78]
[85, 92, 78]
The table didn't change. This is copy-on-write: the two share their data until one of them writes, and then that one gets its own copy. Older tutorials may show the table changing here, so trust what your version prints. To change the table itself, assign to it directly, the same way you added a column. (NumPy behaves differently: there a slice is a view. See NumPy indexing and slicing.)
Recap
| Task | Code |
|---|---|
| One labelled column | pd.Series(list_or_dict) |
| A table | pd.DataFrame(dict_of_lists) |
| Inspect | shape, dtypes, head(), tail(), info(), describe() |
| Select | df["col"] (Series), df[["a", "b"]] (DataFrame) |
| Add a column | df["new"] = rule |
| Calculate | df["col"].sum(), .mean(), .max() |
| Sort | df.sort_values("col", ascending=False) returns a new table |
Try it yourself: in the lesson's practice.py, a small shop table has item, price and qty for a pen, book, bag and cup. Add a total column (price times quantity), sort it biggest first, and check that the totals add up to 116. Or ask an AI tool to write it, then read every line.
Next: reading and writing CSV, Excel and JSON. For the one-pass version aimed at AI engineers, see NumPy and pandas for AI Engineers.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
