Home »
Python »
Python Programs
Select multiple ranges of columns in Pandas DataFrame
Given a pandas dataframe, we have to select multiple ranges of columns.
By Pranit Sharma Last updated : October 03, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Problem statement
Suppose we are given a DataFrame with multiple columns, we need to find a way to select several ranges of columns without specifying all the column names or positions.
Selecting multiple ranges of columns
For this purpose, we will use the numpy.r_ method. It is a simple method to build up arrays quickly.
If the index expression contains comma-separated arrays, then stack them along their first axis but if the index expression contains slice notation or scalars then create a 1-D array with a range indicated by the slice notation.
We need to pass the multiple ranges inside this method so that our resulting array would be a combination of values from multiple ranges.
Let us understand with the help of an example,
Python program to select multiple ranges of columns
# Importing pandas package
import pandas as pd
# Importing numpy package
import numpy as np
# Creating a dictionary
d = {'a':[x for x in range(10,1000,10)]}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display original DataFrame
print("Original Dataframe:\n",df,"\n")
# Converting df column to array
arr = np.array(df['a'])
# Using np.r method on this array
res = np.r_[arr[1:10], arr[15], arr[17], arr[50:100]]
# Display result
print("Result:\n",res)
Output
The output of the above program is:
Python Pandas Programs »