How do I get the index of a column by name?
<p>Given a <code>DataFrame</code></p>

<pre><code>&gt;&gt;&gt; df
   x  y  z
0  1  a  7
1  2  b  5
2  3  c  7
</code></pre>

<p>I would like to find the index of the column by name, e.g., <code>x</code> -> 0, <code>z</code> -> 2, &amp;c.</p>

<p>I can do</p>

<pre><code>&gt;&gt;&gt; list(df.columns).index('y')
1
</code></pre>

<p>but it seems backwards (the <code>pandas.indexes.base.Index</code> class should probably be able to do it without circling back to list).</p>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html" rel="nofollow"><code>Index.get_loc</code></a>:</p>

<pre><code>print (df.columns.get_loc('z'))
2
</code></pre>

<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.searchsorted.html" rel="nofollow"><code>Index.searchsorted</code></a>:</p>

<pre><code>print (df.columns.searchsorted('z'))
2
</code></pre>

<p><strong>Timings</strong>:</p>

<pre><code>In [86]: %timeit (df.columns.get_loc('z'))
The slowest run took 13.42 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 1.99 Âµs per loop

In [87]: %timeit (df.columns.searchsorted('z'))
The slowest run took 10.46 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.48 Âµs per loop
</code></pre>

python python-2.7 pandas