Selecting pandas column by location

Given a Pandas DataFrame, we have to select its column by location. By Pranit Sharma Last updated : September 23, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mainly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and the data.

Selecting pandas column or row is possible in pandas by using pandas.DataFrame.loc or pandas.DataFrame.iloc property. Both properties are used for slicing the data from the pandas DataFrame. Both of these properties are effective and efficient ways of selecting rows or columns.

Selecting pandas column by location

To select pandas column by location, we will use pandas.DataFrame.iloc property. Location means the index value hence, whatever the column we want, we will pass its index in the form of slicing inside pandas.DataFrame.iloc property.

Note

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python program to select pandas column by location

# Importing pandas package
import pandas as pd

# Importing reduce function
from functools import reduce

# Creating  DataFrames
df = pd.DataFrame({
    'Name':['Hari','Om','Rakesh','Mohan','Shilpi','Monica'],
    'Age':[24,25,33,29,27,26],
    'Salary':[19000,33000,94000,75000,67000,50000]
})

# Display DataFrame
print("Created DataFrame:\n",df,"\n")

# Selecting a row where which lies be a particular
# range
result = df.iloc[:, 2]

# Display Result
print("\n",result)

Output

The output of the above program is:

Example: Selecting pandas column by location

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.