The Wayback Machine - https://web.archive.org/web/20240906203541/https://www.geeksforgeeks.org/how-to-select-multiple-columns-in-a-pandas-dataframe/
Open In App

How to select multiple columns in a pandas dataframe

Last Updated : 30 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

In this article, we will discuss all the different ways of selecting multiple columns in a Pandas DataFrame.

Select Multiple Columns in a Pandas Dataframe

Below are the ways by which we can select multiple columns in a Pandas Dataframe:

  • Using Basic Method
  • Using loc[]
  • Using iloc[]
  • Using .ix

Select Multiple Columns in a Pandas Dataframe using Basic Method

In this example, we are using basic method that utilizes the Pandas library to create a DataFrame named ‘df’ from a dictionary of employee data, and then selects and displays only the ‘Name’ and ‘Qualification’ columns from the DataFrame.

Python3




# Import pandas package
import pandas as pd
 
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Age':[27, 24, 22, 32],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# select two columns
df[['Name', 'Qualification']]


Output

Select Second to fourth column

This example uses the pandas library to create a DataFrame ‘df’ from a dictionary of employee data. It then selects and displays all rows while extracting columns 2 to 4 (Age, Address, and Qualification) using DataFrame slicing based on column indices

Python3




# Import pandas package
import pandas as pd
 
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Age':[27, 24, 22, 32],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# select all rows
# and second to fourth column
df[df.columns[1:4]]


Output

Select Multiple Columns in a Pandas Dataframe using loc[]

In this example, we are using loc[] function, we are select two columns. In this example, we creates a DataFrame ‘df’ from a dictionary of employee data. It then selects and displays three rows (index 1 to 3) while extracting specific columns (‘Name’ and ‘Qualification’) using the loc method for label-based indexing.

Python3




# Import pandas package
import pandas as pd
 
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Age':[27, 24, 22, 32],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# select three rows and two columns
df.loc[1:3, ['Name', 'Qualification']]


Output:

Select one to another columns

In this example, we are using loc[] to select column name “Name” to “Address”.

Python3




# Import pandas package
import pandas as pd
 
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Age':[27, 24, 22, 32],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# select two rows and
# column "name" to "Address"
# Means total three columns
df.loc[0:1, 'Name':'Address']


Output:

This Python code, using the pandas library, creates a DataFrame ‘df’ from a dictionary of employee data. It then utilizes the .loc method for label-based indexing to filter and select all columns for the row with index 0, effectively displaying the data for the first employee in the DataFrame.

Python3




# Import pandas package
import pandas as pd
 
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Age':[27, 24, 22, 32],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd']
       }
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# .loc DataFrame method
# filtering rows and selecting columns by label
# format
# df.loc[rows, columns]
# row 1, all columns
df.loc[0, :]


Output:

Select Multiple Columns in Pandas using iloc[]

Example 1: Select first two column

In this example, we are using iloc[] method for integer-location based indexing to select and display all rows and the first two columns (index 0 and 1) of the DataFrame, adhering to the convention that Python slicing is not inclusive of the ending index.

Python3




# Import pandas package
import pandas as pd
 
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Age':[27, 24, 22, 32],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Remember that Python does not
# slice inclusive of the ending index.
# select all rows
# select first two column
df.iloc[:, 0:2]


Output:

Example 2: Select all or some columns, one to another using .iloc

In this example, we are using .iloc method for integer-location based indexing to select and display rows 0 to 1 and columns 1 to 2 (Age and Address) of the DataFrame.

Python3




# Import pandas package
import pandas as pd
 
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Age':[27, 24, 22, 32],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# iloc[row slicing, column slicing]
df.iloc [0:2, 1:3]


Output

Select Multiple Columns in a Pandas Dataframe using .ix

Example: Select all or some columns, one to another using .ix

In this example, we are using .ix indexer to select and print all rows and columns 0 to 2 (Name and Age) from the DataFrame. It is recommended to use .iloc for integer-location based indexing instead, as .ix has been deprecated.

Python3




# Import pandas package
import pandas as pd
 
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Age':[27, 24, 22, 32],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# select all rows and 0 to 2 columns
print(df.ix[:, 0:2])


Output



Similar Reads

How to select and order multiple columns in Pyspark DataFrame ?
In this article, we will discuss how to select and order multiple columns from a dataframe using pyspark in Python. For this, we are using sort() and orderBy() functions along with select() function. Methods UsedSelect(): This method is used to select the part of dataframe columns and return a copy of that newly selected dataframe. Syntax: datafram
2 min read
Select all columns, except one given column in a Pandas DataFrame
DataFrame Data structure are the heart of Pandas library. DataFrames are basically two dimension Series object. They have rows and columns with rows representing the index and columns representing the content. Now, let's see how to Select all columns, except one given column in Pandas DataFrame in Python. Creating a DataFrame: C/C++ Code # import p
2 min read
Randomly Select Columns from Pandas DataFrame
In this article, we will discuss how to randomly select columns from the Pandas Dataframe. According to our requirement, we can randomly select columns from a pandas Database method where pandas df.sample() method helps us randomly select rows and columns. Syntax of pandas sample() method: Return a random selection of elements from an object's axis
3 min read
Select Columns with Specific Data Types in Pandas Dataframe
In this article, we will see how to select columns with specific data types from a dataframe. This operation can be performed using the DataFrame.select_dtypes() method in pandas module. Syntax: DataFrame.select_dtypes(include=None, exclude=None)Parameters : include, exclude : A selection of dtypes or strings to be included/excluded. At least one o
2 min read
Select Rows & Columns by Name or Index in Pandas DataFrame using [ ], loc & iloc
Indexing in Pandas means selecting rows and columns of data from a Dataframe. It can be selecting all the rows and the particular number of columns, a particular number of rows, and all the columns or a particular number of rows and columns each. Indexing is also known as Subset selection. Creating a Dataframe to Select Rows & Columns in Pandas
10 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Add multiple columns to dataframe in Pandas
In Pandas, we have the freedom to add columns in the data frame whenever needed. There are multiple ways to add columns to pandas dataframe. Add multiple columns to a DataFrame using Lists C/C++ Code # importing pandas library import pandas as pd # creating and initializing a nested list students = [['jackma', 34, 'Sydeny', 'Australia'], ['Ritika',
3 min read
Plot Multiple Columns of Pandas Dataframe on Bar Chart with Matplotlib
Prerequisites: PandasMatplotlib In this article, we will learn how to plot multiple columns on bar chart using Matplotlib. Bar Plot is used to represent categories of data using rectangular bars. We can plot these bars with overlapping edges or on same axes. Different ways of plotting bar graph in the same chart are using matplotlib and pandas are
2 min read
Split dataframe in Pandas based on values in multiple columns
In this article, we are going to see how to divide a dataframe by various methods and based on various parameters using Python. To divide a dataframe into two or more separate dataframes based on the values present in the column we first create a data frame. Creating a DataFrame for demonestration C/C++ Code # importing pandas as pd import pandas a
3 min read
How to sort a Pandas DataFrame by multiple columns in Python?
Sorting is a fundamental operation applied to dataframes to arrange data based on specific conditions. Dataframes can be sorted alphabetically or numerically, providing flexibility in organizing information. This article explores the process of sorting a Pandas Dataframe by multiple columns, demonstrating the versatile capabilities of Pandas in han
6 min read
Unnest (Explode) Multiple List Columns In A Pandas Dataframe
An open-source manipulation tool that is used for handling data is known as Pandas. Have you ever encountered a dataset that has columns with data as a list? In such cases, there is a necessity to split that column into various columns, as Pandas cannot handle such data. In this article, we will discuss the same, i.e., unnest or explode multiple li
6 min read
Apply String Methods Across Multiple Columns in a Pandas DataFrame
We are given a dataframe in Pandas with multiple columns, and we want to apply string methods to transform the data within these columns. In this article, we will explore three different approaches to applying string methods to multiple columns of a dataframe. Apply String Methods to Multiple Columns of a DataframeBelow are the possible approaches
2 min read
How to drop one or multiple columns in Pandas Dataframe
Let’s discuss how to drop one or multiple columns in Pandas Dataframe. To Delete a column from a Pandas DataFrame or Drop one or multiple columns in a Pandas Dataframe can be achieved in multiple ways. # Drop column 'B'df = df.drop('B', axis=1)# Drop columns multiple column df = df.drop(['B', 'C'], axis=1)There are various methods to drop one or mu
10 min read
Select columns in PySpark dataframe
In this article, we will learn how to select columns in PySpark dataframe. Function used: In PySpark we can select columns using the select() function. The select() function allows us to select single or multiple columns in different formats. Syntax: dataframe_name.select( columns_names ) Note: We are specifying our path to spark directory using th
4 min read
PySpark - Select Columns From DataFrame
In this article, we will discuss how to select columns from the pyspark dataframe. To do this we will use the select() function. Syntax: dataframe.select(parameter).show() where, dataframe is the dataframe nameparameter is the column(s) to be selectedshow() function is used to display the selected column Let's create a sample dataframe C/C++ Code #
2 min read
PySpark DataFrame - Select all except one or a set of columns
In this article, we are going to extract all columns except a set of columns or one column from Pyspark dataframe. For this, we will use the select(), drop() functions. But first, let's create Dataframe for demonestration. C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSess
2 min read
How to join datasets with same columns and select one using Pandas?
It is usual that in Data manipulation operations, as the data comes from different sources, there might be a need to join two datasets to one. In this article, let us discuss how to join datasets with the same columns in python. Using Pandas concat() Python has a package called pandas that provides a function called concat that helps us to join two
2 min read
How to select the rows of a dataframe using the indices of another dataframe?
Prerequisites: PandasRandom Using Pandas module it is possible to select rows from a data frame using indices from another data frame. This article discusses that in detail. It is advised to implement all the codes in jupyter notebook for easy implementation. Approach:Import moduleCreate first data frame. In the example given below choice(), randin
2 min read
Select row with maximum and minimum value in Pandas dataframe
Let's see how can we select rows with maximum and minimum values in Pandas Dataframe with help of different examples using Python. Creating a Dataframe to select rows with max and min values in Dataframe C/C++ Code # importing pandas and numpy import pandas as pd import numpy as np # data of 2018 drivers world championship dict1 = {'Driver': ['Hami
2 min read
Select any row from a Dataframe in Pandas | Python
In this article, we will learn how to get the rows from a dataframe as a list, without using the functions like ilic[]. There are multiple ways to do get the rows as a list from given dataframe. Let’s see them will the help of examples. # importing pandas as pd import pandas as pd # Create the dataframe df = pd.DataFrame({'Date':['10/2/2011', '11/2
1 min read
Select any row from a Dataframe using iloc[] and iat[] in Pandas
In this article, we will learn how to get the rows from a dataframe as a list, using the functions ilic[] and iat[]. There are multiple ways to do get the rows as a list from given dataframe. Let’s see them will the help of examples. Python Code import pandas as pd # Create the dataframe df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/20
2 min read
Select first or last N rows in a Dataframe using head() and tail() method in Python-Pandas
Let’s discuss how to select top or bottom N number of rows from a Dataframe using head() & tail() methods. 1) Select first N Rows from a Dataframe using head() method of Pandas DataFrame : Pandas head() method is used to return top n (5 by default) rows of a data frame or series Syntax: Dataframe.head(n). Parameters: (optional) n is integer value,
2 min read
How to Select Rows from Pandas DataFrame?
pandas.DataFrame.loc is a function used to select rows from Pandas DataFrame based on the condition provided. In this article, let's learn to select the rows from Pandas DataFrame based on some conditions. Syntax: df.loc[df['cname'] 'condition'] Parameters: df: represents data frame cname: represents column name condition: represents condition on w
2 min read
How to Select single column of a Pandas Dataframe?
In this article, we will discuss how to select a single column in a data frame. Now let us try to implement this using Python. First, let's create a dataframe C/C++ Code # importing pandas as library import pandas as pd # creating data frame: df = pd.DataFrame({'name': ['Akash', 'Ayush', 'Ashish', 'Diksha', 'Shivani'], 'Age': [21, 25, 23, 22, 18],
1 min read
Select Pandas dataframe rows between two dates
Prerequisites: pandas Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for
2 min read
How to randomly select rows from Pandas DataFrame
In Pandas, we can randomly select any row from the Pandas DataFrame. In this article, we are going to see how to randomly select rows from Pandas Dataframe. Creating Sample Pandas DataFrameFirst, we will create a sample Pandas DataFrame that we will use further in our article. C/C++ Code # Import pandas package import pandas as pd # Define a dictio
5 min read
Split single column into multiple columns in PySpark DataFrame
pyspark.sql.functions provide a function split() which is used to split DataFrame string Column into multiple columns. Syntax: pyspark.sql.functions.split(str, pattern, limit=- 1) Parameters: str: str is a Column or str to split.pattern: It is a str parameter, a string that represents a regular expression. This should be a Java regular expression.l
4 min read
How to Order PysPark DataFrame by Multiple Columns ?
In this article, we are going to order the multiple columns by using orderBy() functions in pyspark dataframe. Ordering the rows means arranging the rows in ascending or descending order, so we are going to create the dataframe using nested list and get the distinct data. orderBy() function that sorts one or more columns. By default, it orders by a
2 min read
How to rename multiple columns in PySpark dataframe ?
In this article, we are going to see how to rename multiple columns in PySpark Dataframe. Before starting let's create a dataframe using pyspark: C/C++ Code # importing module import pyspark from pyspark.sql.functions import col # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving
2 min read
Drop One or Multiple Columns From PySpark DataFrame
In this article, we will discuss how to drop columns in the Pyspark dataframe. In pyspark the drop() function can be used to remove values/columns from the dataframe. Syntax: dataframe_name.na.drop(how=”any/all”,thresh=threshold_value,subset=[“column_name_1″,”column_name_2”]) how – This takes either of the two values ‘any’ or ‘all’. ‘any’, drop a r
3 min read