The Wayback Machine - https://web.archive.org/web/20250114231843/https://www.geeksforgeeks.org/how-to-take-column-slices-of-dataframe-in-pandas/
Open In App

How to take column-slices of DataFrame in Pandas?

Last Updated : 10 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn how to slice a DataFrame column-wise in Python. DataFrame is a two-dimensional tabular data structure with labeled axes. i.e. columns.

Creating Dataframe to slice columns

Python
# importing pandas
import pandas as pd

# Using DataFrame() method from pandas module
df1 = pd.DataFrame({"a": [1, 2, 3, 4, 5, 6, 7], 
                    "b": [2, 3, 4, 2, 3, 4, 5], 
                    "c": [3, 4, 5, 2, 3, 4, 5], 
                    "d": [4, 5, 6, 2, 3, 4, 5], 
                    "e": [5, 6, 7, 2, 3, 4, 5]})

display(df1)

Output:

Method 1: Slice Columns in pandas using reindex

Slicing column from ‘c’ to ‘b’.

Python
df2 = df1.reindex(columns = ['c','b'])
print(df2)

Output:

Method 2: Slice Columns in pandas using loc[]

The df.loc[] is present in the Pandas package loc can be used to slice a Dataframe using indexing. Pandas DataFrame.loc attribute accesses a group of rows and columns by label(s) or a boolean array in the given DataFrame.

Syntax: [ : , first : last : step]

Example 1:

Slicing column from ‘b’ to ‘d’ with step 2.

Python
df2 = df1.loc[:, "b":"d":2]
print(df2)

Output:

Example 2:

Slicing column from ‘c’ to ‘e’ with step 1.

Python
df2 = df1.loc[:, "c":"e":1]
print(df2)

Output:

Method 3: Slice Columns in pandas using iloc[]

The iloc is present in the Pandas package. The iloc can be used to slice a Dataframe using indexing. df.iloc[] method is used when the index label of a data frame is something other than numeric series of 0, 1, 2, 3….n or in case the user doesn’t know the index label. Rows can be extracted using an imaginary index position that isn’t visible in the data frame.

Syntax: [ start : stop : step]

Example 1:

Slicing column from ‘1’ to ‘3’ with step 1.

Python
df2 = df1.iloc[:, 1:3:1]
print(df2)

Output:

Example 2:

Slicing column from ‘0’ to ‘3’ with step 2.

Python
df2 = df1.iloc[:, 0:3:2]
print(df2)

Output:

Screenshot-2024-07-09-160446

Output



Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today


Next Article

Similar Reads

three90RightbarBannerImg