1

Say I have a pandas dataframe. I can access the columns either by their name or by their index.

Is there a simple way in which I can retrieve the column index given its name?

2
  • 2
    Your question is unclear as we have 3 answers here, are you asking how to get just the columns: list(df) or df.columns or asking how to get the column array index position by name? Commented Jun 9, 2016 at 10:42
  • sorry for not being clear, the second one Commented Jun 9, 2016 at 11:29

2 Answers 2

1

Use get_loc on the columns Index object to return the ordinal index value:

In [283]:
df = pd.DataFrame(columns=list('abcd'))
df

Out[283]:
Empty DataFrame
Columns: [a, b, c, d]
Index: []

In [288]:
df.columns.get_loc('b')

Out[288]:
1
Sign up to request clarification or add additional context in comments.

Comments

1

What do you mean by index exactly?

I bet you are referring to index as a list index, right?

Because Pandas has another kind of index too.

From my first understandying, you can do the following:

my_df = pd.DataFrame(columns=['A', 'B', 'C'])
my_columns = my_df.columns.tolist()
print my_columns # yields ['A', 'B', 'C'], therefore you can recover the index by just doing the following
my_columns.index('C') #yields 2

2 Comments

This returned AttributeError: 'Index' object has no attribute 'index'
sorry, check it again. I converted it to a list now. i am on my mobile, so i may commit some mistakes =P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.