What is the problem

U have a DataFrame and u need to select specific slices, maybe:

Before you begin

Recall the structure of a DataFrame

The Diagram

Link to original

I’ll demonstrate selection on the example below

Its Tabular/Pythonic Form

(index)TeamScore
0P_00Red5
1P_01Blue10
2P_02Red15

Its visual form

100%


The Strategy

Column Selection

To select column(s), u do the following:

  1. determine the selector
    • select by column label (it doesn’t have to be a string)
# an example
selector = 'Team'

  1. use that selector
    • used on the [] operator.
column = df[selector] 

Multi-Column Selection

If u want to select multiple columns, simply change the selector to a list of their identifiers (usually their names).

Rows Selection

To select row(s), u do the following:

  1. determine the selector
  2. use that selector

Case A

(direct lookup)

  1. determine the selector
    • select by its index label (it doesn’t have to be a string)
# an example
selector = 'P_01'

  1. use that selector
    • used on the .loc operator.
row = df.loc['P_01'] 

Case B

(direct lookup)

  1. determine the selector
    • select by its position (the selector is always an int)
# an example
selector = 1

  1. use that selector
    • used on the .iloc operator.
row = df.iloc[1] 

Case C

(*lookup based on some “criteria”)

  1. determine the selector
    • select by some column value criteria (the selector usually is a pandas boolean mask)
# an example
selector = df['Team'] == 'Red' # select rows that their 'Team' column value is 'Red'
# it evaluates to this (a pandas bool mask)
"""
P_00   True 
P_01   False
P_02   True
"""

  1. use that selector
    • used on the [] operator.
rows = df[selector]

Multi-Row Selection

In direct lookup (Case A: .loc and Case B: .iloc), if u want to select multiple rows, simply change the selector to a list of their identifiers.

Row then Column selection

You can also use a row and then column selector, using the .loc operator.

# syntax
result = df.loc[row_selector, column_selector]

Connections