Examples
import numpy as np
import pandas as pd
df = pd.DataFrame([[2, 3], [5, 6], [8, 9]],
index=['cobra', 'viper', 'sidewinder'],
columns=['max_speed', 'shield'])
df
Single label:
df.loc['viper']
List of labels:
df.loc[['viper', 'sidewinder']]
Single label for row and column:
df.loc['cobra', 'shield']
Slice with labels for row and single label for column. As mentioned above, note that both
the start and stop of the slice are included.
df.loc['cobra':'viper', 'max_speed']
Boolean list with the same length as the row axis:
df.loc[[False, False, True]]
Conditional that returns a boolean Series
df.loc[df['shield'] > 6]
Conditional that returns a boolean Series with column labels specified:
df.loc[df['shield'] > 6, ['max_speed']]
Callable that returns a boolean Series:
df.loc[lambda df: df['shield'] == 9]
Setting values
Set value for all items matching the list of labels:
df.loc[['viper', 'sidewinder'], ['shield']] = 30
df
Set value for an entire row:
df.loc['cobra'] =10
df
Set value for an entire column:
df.loc[:, 'max_speed'] = 30
df
Set value for rows matching callable condition:
df.loc[df['shield'] > 35] = 0
df
Getting values on a DataFrame with an index that has integer labels
df = pd.DataFrame([[2, 3], [5, 6], [8, 9]],
index=[2, 3, 4], columns=['max_speed', 'shield'])
df
Slice with integer labels for rows. As mentioned above, note that both the start and stop
of the slice are included:
df.loc[2:4]
Getting values with a MultiIndex
A number of examples using a DataFrame with a MultiIndex:
tuples = [
('cobra', 'm1'), ('cobra', 'm2'),
('sidewinder', 'm1'), ('sidewinder', 'm2'),
('viper', 'm2'), ('viper', 'm3')
]
index = pd.MultiIndex.from_tuples(tuples)
values = [[14, 4], [0, 6], [20, 30],
[2, 4], [5, 1], [26, 46]]
df = pd.DataFrame(values, columns=['max_speed', 'shield'], index=index)
df
Single label:
df.loc['cobra']
Single index tuple:
df.loc[('cobra', 'm2')]
Single label for row and column:
df.loc['cobra', 'm1']
Single tuple:
df.loc[[('cobra', 'm2')]]
Single tuple for the index with a single label for the column:
df.loc[('cobra', 'm1'), 'shield']
Slice from index tuple to single label:
df.loc[('cobra', 'm1'):'viper']
Slice from index tuple to index tuple:
df.loc[('cobra', 'm1'):('viper', 'm2')]