Get first letter of index?
<p>I have a pandas dataframe <code>df</code> that looks like this:</p>

<pre><code>            population
n
France      66.03
Italy       59.83
</code></pre>

<p>I want to get the first letter of the index label, for each row, and set it as a new column so that I can start doing analysis with it. How can I do this?</p>

<p>Right now I'm doing this:</p>

<pre><code>def get_first_letter(row):
    return row[0]
df1 = df.reset_index()
df1.first_letter = df1.n.apply(get_first_letter)
</code></pre>

<p>Is there a better way?</p>

<p>You could use the <a href="http://pandas.pydata.org/pandas-docs/version/0.18.1/generated/pandas.Index.get_level_values.html#pandas-index-get-level-values" rel="nofollow"><code>get_level_values</code> method</a> to obtain the index label. Then <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="nofollow">use <code>str[0]</code></a> to obtain the first letter:</p>

<pre><code>In [29]: df = pd.DataFrame({'population':[66.03,59.83]}, index=pd.Series(['France','Italy'], name='n')); df
Out[29]: 
        population
n                 
France       66.03
Italy        59.83

In [30]: df['first_letter'] = df.index.get_level_values('n').str[0]; df
Out[30]: 
        population first_letter
n                              
France       66.03            F
Italy        59.83            I
</code></pre>

python pandas