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>I think there's nothing wrong with what you're doing. There are two things which you may do differently</p>

<ol>
<li>use lambda or list comprehension instead of the named function</li>
<li>set the index directly instead of reseting it.</li>
</ol>

<p>Like this:</p>

<pre><code>df1.n.apply(lambda x: x[0])
</code></pre>

<p>or</p>

<pre><code>df1.set_index(pd.Index((x[0] for x in df1.index)))
</code></pre>

python pandas