Friday, September 1, 2017

Python pandas iloc vs ix vs loc explanation

"""
loc is label based indexing so basically looking up a value in a row
iloc is integer row based indexing
ix is a general method that first performs label based, if that fails then it falls to integer based
"""
import pandas as pd

df = pd.DataFrame({'A': ['abc', 'xyz', 'pqr'], 'B': [25, 50, 75]}, index = [50, 100, 150])
print(df)

print(df.loc[100, :])  # subset dataframe df if index value = 100 across all columns

print(df.iloc[1, :])   # subset dataframe df for row = 1 across all columns

df = pd.DataFrame({'A': ['abc', 'xyz', 'pqr'], 'B': [25, 50, 75]}, index = ['50', '100', '150'])

# the following yield same result
print(df.ix['50', :])
print(df.ix[1, :])

1 comment:

  1. iloc and loc are two important concepts when it comes to website accessibility. Both of them are important for making your content accessible to screen reader users.
    https://codeprozone.com/code/python/118899/iloc-and-loc.html

    ReplyDelete