
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
How to get column index from column name in Python Pandas?
To get column index from column name in Python Pandas, we can use the get_loc() method.
Steps −
- Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
- Print the input DataFrame, df.
- Find the columns of DataFrame, using df.columns.
- Print the columns from Step 3.
- Initialize a variable column_name.
- Get the location, i.e., of index for column_name.
- Print the index of the column_name.
Example −
import pandas as pd df = pd.DataFrame( { "x": [5, 2, 7, 0], "y": [4, 7, 5, 1], "z": [9, 3, 5, 1] } ) print"Input DataFrame 1 is:\n", df columns = df.columns print"Columns in the given DataFrame: ", columns column_name = "z" column_index = columns.get_loc(column_name) print"Index of the column ", column_name, " is: ", column_index column_name = "x" column_index = columns.get_loc(column_name) print"Index of the column ", column_name, " is: ", column_index column_name = "y" column_index = columns.get_loc(column_name) print"Index of the column ", column_name, " is: ", column_index
Output
Input DataFrame 1 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Columns in the given DataFrame: Index(['x', 'y', 'z'], dtype='object') Index of the column z is: 2 Index of the column x is: 0 Index of the column y is: 1
- Related Articles
- Python Pandas - Get unique values from a column
- Python – Drop a level from a multi-level column index in Pandas dataframe
- Python – Drop multiple levels from a multi-level column index in Pandas dataframe
- Python Pandas - Subset DataFrame by Column Name
- Python - How to select a column from a Pandas DataFrame
- How to get the list of column headers from a Pandas DataFrame?
- Rename column name with an index number of the CSV file in Pandas
- How to use column index instead of column name while using group_by of dplyr in R?
- How to add column from another DataFrame in Pandas?
- How to delete a column from Pandas DataFrame
- How to get row index or column index based on their names in R?
- Python Pandas - Alter index name
- Python - Rename column names by index in a Pandas DataFrame without using rename()
- How to get the sum of a specific column of a dataframe in Pandas Python?
- How to delete a column from a Pandas DataFrame?

Advertisements