Get column index from column name of a given Pandas DataFrame

import pandas as pd

# Sample DataFrame
data = {‘A’: [1, 2, 3], ‘B’: [4, 5, 6], ‘C’: [7, 8, 9]}
df = pd.DataFrame(data)

# Function to get column index by column name
def get_column_index(df, column_name):
try:
return df.columns.get_loc(column_name)
except KeyError:
return f”Column ‘{column_name}’ not found”

# Example usage
column_name = ‘B’
index = get_column_index(df, column_name)
print(f”The index of column ‘{column_name}’ is: {index}”)

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top