Python for Excel users · Lesson 2 of 14

A sheet is a DataFrame: rows and columns

How an Excel sheet maps to a pandas DataFrame: headers become column names, cell references become df.loc, and ranges become slices.

About 15 minutes · code runs in your browser, nothing to install

In Excel you point at data by letter and number: B3, A2:A8, C:C. In pandas you point at it by column name and row label. Once you see the mapping, everything else in this course gets easier.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "City": ["Lisbon", "Porto", "Madrid", "Lyon", "Turin"],
    "Units": [120, 85, 240, 60, 155],
    "Price": [2.5, 2.5, 3.0, 2.75, 3.0],
})
print(df)
print(df.shape)
print(list(df.columns))
Output
     City  Units  Price
0  Lisbon    120   2.50
1   Porto     85   2.50
2  Madrid    240   3.00
3    Lyon     60   2.75
4   Turin    155   3.00
(5, 3)
['City', 'Units', 'Price']

shape gives (rows, columns). The header row is not counted as a row.

Columns: C:C becomes df["Units"]

In Excel the units are in column B, so =SUM(B:B). In pandas you use the header name: df["Units"]. One column is called a Series. It has the same summary methods as Excel functions: .sum(), .mean(), .max(), .min() and .count().

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "City": ["Lisbon", "Porto", "Madrid", "Lyon", "Turin"],
    "Units": [120, 85, 240, 60, 155],
})
print(df["Units"].sum())
print(df["Units"].mean())
print(df["Units"].max())
print(df[["City", "Units"]].head(2))
Output
660
132.0
240
     City  Units
0  Lisbon    120
1   Porto     85

Two pairs of brackets, df[["City", "Units"]], pick several columns and give back a smaller table. .head(2) shows the first 2 rows.

Note: Because pandas uses names, inserting a new column never breaks your formulas. Excel moves cell references such as C:C when a column is inserted, but a fixed column number does not move: =VLOOKUP(A2, B:E, 3, FALSE) quietly returns the wrong column after someone inserts one inside B:E.

Cells: B3 becomes df.loc[row, column]

df.loc[row_label, "Column"] reads one cell. Row labels start at 0, and the header is not a row, so Excel row 2 (the first data row) is label 0. df.iloc[row, col] uses positions instead, counting from 0 for both.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "City": ["Lisbon", "Porto", "Madrid", "Lyon", "Turin"],
    "Units": [120, 85, 240, 60, 155],
})
print(df.loc[2, "City"])
print(df.loc[2, "Units"])
print(df.iloc[0, 1])
df.loc[4, "Units"] = 160
print(df.loc[1:3, "Units"].tolist())
Output
Madrid
240
120
[85, 240, 60]

df.loc[1:3, ...] includes row 3: unlike most Python ranges, loc keeps both ends, like the Excel range B3:B5.

Rows from the top and the bottom

.head(n) and .tail(n) show the first or last rows, like scrolling to the top or pressing Ctrl+Down. len(df) is the number of data rows, like =COUNTA(A:A)-1.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "City": ["Lisbon", "Porto", "Madrid", "Lyon", "Turin"],
    "Units": [120, 85, 240, 60, 155],
})
print(df.tail(2))
print("Rows:", len(df))
Output
    City  Units
3   Lyon     60
4  Turin    155
Rows: 5

Use a column as the row label

If every row has a unique name, such as a product code or a city, you can make it the row label with set_index. Then you read cells by name, which feels like a lookup.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "City": ["Lisbon", "Porto", "Madrid"],
    "Units": [120, 85, 240],
})
by_city = df.set_index("City")
print(by_city)
print(by_city.loc["Madrid", "Units"])
Output
        Units
City
Lisbon    120
Porto      85
Madrid    240
240

✎ Exercise

From the table, print the price in the row labelled 3, then print the total of the Units column, then print the Product and Units columns only.

Hint: df.loc[3, "Price"] reads one cell; df[["Product", "Units"]] uses a list of names inside the brackets.

Your codewrite your answer, then Run
import pandas as pd

df = pd.DataFrame({
    "Product": ["Pen", "Pad", "Ink", "Clip", "Tape"],
    "Units": [40, 12, 7, 90, 15],
    "Price": [1.2, 3.5, 6.0, 0.1, 2.25],
})
# your code here

Expected output:

0.1
164
  Product  Units
0     Pen     40
1     Pad     12
2     Ink      7
3    Clip     90
4    Tape     15
Show a solution
Solutioneditable
import pandas as pd

df = pd.DataFrame({
    "Product": ["Pen", "Pad", "Ink", "Clip", "Tape"],
    "Units": [40, 12, 7, 90, 15],
    "Price": [1.2, 3.5, 6.0, 0.1, 2.25],
})
print(df.loc[3, "Price"])
print(df["Units"].sum())
print(df[["Product", "Units"]])
Output
0.1
164
  Product  Units
0     Pen     40
1     Pad     12
2     Ink      7
3    Clip     90
4    Tape     15

Check yourself

1. Excel's first data row is row 2. What is its row label in a new DataFrame?

2. Which is the pandas version of =SUM(C:C) when column C has the header Price?

3. What does df.loc[1:3, "Units"] return?

Spotted a mistake on this page? Tell us