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>Similar to the other answer:</p>

<pre><code>df.index.set_levels(df.index.map(lambda x: (x[0], x[1].strip())), inplace=True)
</code></pre>

python string pandas multi-index