strip whitespace in pandas MultiIndex index columns values
<p>i have a MultiIndex dataframe of mix datatypes. One of the index columns values has trailing whitespaces. How can i strip these trailing whitespace for the index columns. here is the sample code:</p>

<pre><code>import pandas as pd
idx = pd.MultiIndex.from_product([['1.0'],['NY   ','CA  ']], names=['country_code','state'])
df = pd.DataFrame({'temp':['78','85']},index = idx)
</code></pre>

<p>One solution is to reset the index, strip the whitespaces for the desired column and again set index. Something like below:</p>

<pre><code>df = df.reset_index()
df['state'] = df['state'].str.strip()
df =  df.set_index(['country_code','state'],drop=True)
</code></pre>

<p>but this is a roundabout way, is there a more direct way to strip the whitespaces in the index itself?</p>

<p>You can use <code>.index.set_levels()</code> and <code>.index.get_level_values()</code> to manipulate the index at a specific level:</p>

<pre><code>df.index.set_levels(df.index.get_level_values(level = 1).str.strip(), 
                    level = 1, inplace=True)

df.index
# MultiIndex(levels=[['1.0'], ['NY', 'CA']],
#            labels=[[0, 0], [1, 0]],
#            names=['country_code', 'state'])
</code></pre>

python string pandas multi-index