Search⌘ K
AI Features

Indexing by Position

Explore how to index pandas DataFrames by position using iloc. Understand selecting rows and columns with scalars, lists, slices, and functions to extract data as Series or DataFrames. Gain hands-on knowledge of versatile position-based data selection techniques.

We'll cover the following...

The iloc attribute gives us the ability to pull out rows and columns from a DataFrame. Here we pull out row position 1. Note that this returns the result as a Series (even though it represents a row):

Python 3.8
def tweak_siena_pres(df):
def int64_to_uint8(df_):
cols = df_.select_dtypes('int64')
return (df_
.astype({col:'uint8' for col in cols}))
return (df
.rename(columns={'Seq.':'Seq'}) # 1
.rename(columns={k:v.replace(' ', '_') for k,v in
{'Bg': 'Background',
'PL': 'Party leadership', 'CAb': 'Communication ability',
'RC': 'Relations with Congress', 'CAp': 'Court appointments',
'HE': 'Handling of economy', 'L': 'Luck',
'AC': 'Ability to compromise', 'WR': 'Willing to take risks',
'EAp': 'Executive appointments', 'OA': 'Overall ability',
'Im': 'Imagination', 'DA': 'Domestic accomplishments',
'Int': 'Integrity', 'EAb': 'Executive ability',
'FPA': 'Foreign policy accomplishments',
'LA': 'Leadership ability',
'IQ': 'Intelligence', 'AM': 'Avoid crucial mistakes',
'EV': "Experts' view", 'O': 'Overall'}.items()})
.astype({'Party':'category'}) # 2
.pipe(int64_to_uint8) # 3
.assign(Average_rank=lambda df_:(df_.select_dtypes('uint8') # 4
.sum(axis=1).rank(method='dense').astype('uint8')),
Quartile=lambda df_:pd.qcut(df_.Average_rank, 4,
labels='1st 2nd 3rd 4th'.split())
)
)
import pandas as pd
url = 'https://github.com/mattharrison/datasets/raw/master/data/'\
'siena2018-pres.csv'
df = pd.read_csv(url, index_col=0)
pres = tweak_siena_pres(df)
print(pres.iloc[1])

In the next example, instead of passing in scalar position, we’re going to pass in row position 1 in a list. Sometimes we’ll hear people tell ...