How to apply the slicing indexer to the pandas DataFrame.iloc attribute?

PandasServer Side ProgrammingProgramming

The pandas DataFrame.iloc is an attribute that is used to access the elements of the DataFrame using integer-location-based index values.

The attribute .iloc only takes the integer values which are specifying the row and column index positions. Generally, the position-based index values are represented from 0 to length-1.

Beyond this range only we can access the DataFrame elements otherwise it will raise an “IndexError”. But the slice indexer won’t raise “IndexError” for out-of-bound index value, because it allows out-of-bounds index values.

Example 1

In this following example, we have applied the slicing indexer to the iloc attribute to access the values from the 1st -3rd row. Here, 3 is excluded.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame([['a','b'],['c','d'],['e','f'],['g','h']], columns=['col1','col2'])

print("DataFrame:")
print(df)

# Access the elements using slicing indexer
result = df.iloc[1:3]
print("Output:")
print(result)

Output

The output is given below −

DataFrame:
  col1 col2
0    a   b
1    c   d
2    e   f
3    g   h

Output:
 col1 col2
1   c   d
2   e   f

The iloc attribute successfully accessed the 2 rows elements from the given DataFrame by specifying the slicing indexer object to the “.iloc” attribute.

Example 2

Now, let us apply the slicing indexer with negative bound values to the iloc attribute.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame([['a','b'],['c','d'],['e','f'],['g','h']], columns=['col1','col2'])

print("DataFrame:")
print(df)

# Apply slicing indexer with negative bound values
result = df.iloc[-4:-1]
print("Output:")
print(result)

Output

The output is given below −

DataFrame:
 col1 col2
0   a   b
1   c   d
2   e   f
3   g   h

Output:
 col1 col2
0  a   b
1  c   d
2  e   f

The negative bound values [-4:-1] are given to the iloc attribute. Then it returns a new DataFrame with accessed elements

raja
Updated on 08-Mar-2022 11:23:24

Advertisements