How to access pandas DataFrame elements using the .iloc attribute?

PandasServer Side ProgrammingProgramming

The pandas.DataFrame.iloc attribute is used to access elements from a pandas DataFrame using the integer position. And It is very similar to the pandas.DataFrame “iat” attribute but the difference is, the “iloc” attribute can access a group of elements whereas the “iat” attribute accesses only a single element.

The “.iloc” attribute allows inputs like an integer value, a list of integer values, and a slicing object with integers, and boolean array, etc.

The attribute will raise an “IndexError” if the requested index is out of bounds, except for the slicing indexer object.

Example 1

In this following example, we created a pandas DataFrame using a nested list with integer values. After that, we have applied the iloc attribute with a single integer value.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame([[1,2,3,4],[10,20,30,40],[100,200,300,400]], columns=list('abcd'))

print("DataFrame:")
print(df)

# Access the elements using iloc attribute
result = df.iloc[0]
print("Output:")
print(result)

Output

The output is given below −

DataFrame:
    a   b   c   d
0   1   2   3   4
1  10  20  30  40
2 100 200 300 400

Output:
a    1
b    2
c    3
d    4
Name: 0, dtype: int64

The iloc attribute accessed the entire 0th-row from the given DataFrame.

Example 2

Let’s access the elements from pandas.DataFrame by providing the list of integer values to the iloc attribute. In this example, we have specified [0,1] to the “iloc” attribute.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame([[1,2,3,4],[10,20,30,40],[100,200,300,400]], columns=list('abcd'))

print("DataFrame:")
print(df)

# Access the elements using a list of integers
result = df.iloc[[0,1]]
print("Output:")
print(result)

Output

The output is given below −

DataFrame:
    a   b   c   d
0   1   2   3   4
1  10  20  30  40
2 100 200 300 400

Output:
   a  b  c  d
0  1  2  3  4
1 10 20 30 40

We have successfully accessed the 0th and 1st-row elements from the pandas DataFrame using the “iloc” attribute. As a result, it returns a new DataFrame object which is displayed in the above output block.

raja
Updated on 08-Mar-2022 09:49:27

Advertisements