apocalypsis
apocalypsis

Reputation: 571

Retrieve pandas dataframe column index

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?

Upvotes: 1

Views: 990

Answers (2)

Ricardo Silveira
Ricardo Silveira

Reputation: 1243

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

Upvotes: 1

EdChum
EdChum

Reputation: 393973

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

Upvotes: 1

Related Questions