Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 on the DataFrame's columns Index object.
Syntax
df.columns.get_loc(column_name)
Parameters
- column_name − The name of the column whose index you want to find
Return Value
Returns an integer representing the positional index of the specified column.
Example
Let's create a DataFrame and find the index of different columns ?
import pandas as pd
# Create a DataFrame
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print("Input DataFrame:")
print(df)
print("\nColumns in the DataFrame:", list(df.columns))
# Get index for different columns
column_name = "z"
column_index = df.columns.get_loc(column_name)
print(f"\nIndex of column '{column_name}': {column_index}")
column_name = "x"
column_index = df.columns.get_loc(column_name)
print(f"Index of column '{column_name}': {column_index}")
column_name = "y"
column_index = df.columns.get_loc(column_name)
print(f"Index of column '{column_name}': {column_index}")
Input DataFrame: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Columns in the DataFrame: ['x', 'y', 'z'] Index of column 'z': 2 Index of column 'x': 0 Index of column 'y': 1
Alternative Method Using List Index
You can also convert columns to a list and use the index() method ?
import pandas as pd
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie"],
"age": [25, 30, 35],
"city": ["NYC", "LA", "Chicago"]
})
# Using list index method
column_index = list(df.columns).index("age")
print(f"Index of 'age' column: {column_index}")
# Using get_loc method
column_index = df.columns.get_loc("city")
print(f"Index of 'city' column: {column_index}")
Index of 'age' column: 1 Index of 'city' column: 2
Comparison
| Method | Performance | Error Handling |
|---|---|---|
df.columns.get_loc() |
Faster | Raises KeyError for missing columns |
list(df.columns).index() |
Slower | Raises ValueError for missing columns |
Conclusion
Use df.columns.get_loc(column_name) to get the positional index of a column by name. This method is efficient and specifically designed for pandas Index objects.
Advertisements
