Skip to content
Advertisement

applymap() does not work on Pandas MultiIndex Slice

I have an hierarchical dataset:

df = pd.DataFrame(np.random.rand(6,6),
              columns=[['A','A','A','B','B','B'],
                       ['mean', 'max', 'avg']*2],
              index=pd.date_range('20000103', periods=6))

I want to apply a function to all values under the columns A. I can set the value to something:

df.loc[slice(None), 'A'] = 1

Easy enough. Now, instead of assigning a value, if I want to apply a mapping to this MultiIndex slice, it does not work.

For example, let me apply a simple formatting statement:

df.loc[slice(None), 'A'].applymap('{:.2f}'.format)

This step works fine. However, I cannot assign this to the original df:

df.loc[slice(None), 'A'] = df.loc[slice(None), 'A'].applymap('{:.2f}'.format)

Everything turns into a NaN. Any help would be appreciated.

Advertisement

Answer

You can do it in a couple of ways:

df['A'] = df['A'].applymap('{:.2f}'.format)

or (this will keep the original dtype)

df['A'] = df['A'].round(2)

or as a string

df['A'] = df['A'].round(2).astype(str)
Advertisement