How to create a DataFrame series as a sub-string of a DataFrame Index?
<p>I have a Pandas DataFrame which has a 5-digit string as its index (the index is a 5 digit zip code). I'd need to create another series in the DataFrame which is the first three characters of the index (i.e. the 3-Digit zip code).</p>

<p>As an example, if the index for a row is "32779", I'd like the new series' value to be "327".</p>

<p>I thought a Lambda function may work e.g.</p>

<pre><code>fte5['Zip3'] = fte5.index.astype(str).apply(lambda x: x[:3])
</code></pre>

<p>But this gives an error</p>

<p>consider the <code>pd.DataFrame</code> <code>fte5</code></p>

<pre><code>fte5 = pd.DataFrame(np.ones((3, 2)), ['01234', '34567', '56789'], ['X', 'Y'])
fte5
</code></pre>

<p><a href="https://i.stack.imgur.com/1AHww.png" rel="nofollow"><img src="https://i.stack.imgur.com/1AHww.png" alt="enter image description here"></a></p>

<p>If you already have 5 digit zipcodes that start with <code>0</code> then they must be <code>str</code> already.  The simplest way to get at the first 3 characters in a vectorized way is to use the <code>.str</code> string accessor rather than use <code>apply</code>.</p>

<pre><code>fte5.index.str[:3]

Index(['012', '345', '567'], dtype='object')
</code></pre>

<p>We can assign it to <code>fte5['Zip3']</code> with <code>insert</code></p>

<pre><code>fte5.insert(2, 'Zip3', fte5.index[:3])
</code></pre>

python pandas dataframe