I am writing a function that recodes Pandas DataFrame index objects from a recode
dictionary.
recodes = {'sales' : 'CurrentSales', 'cash' : 'US$' }
- Is there any built in method for this?
- What is an efficient way of doing this?
Using an example:
import pandas as pd
import io
text = '''\
STK_ID RPT_Date sales cash
000568 20120930 80.093 57.488
000596 20120930 32.585 26.177
000799 20120930 14.784 8.157
'''
df = pd.read_csv(io.BytesIO(text), delimiter = ' ',
converters = {0:str})
df.set_index(['STK_ID','RPT_Date'], inplace = True)
What I have implemented is essentially:
nw_idx = ['']*len(df.columns)
for key in recodes.keys():
for idx, colname in enumerate(df.columns):
if colname == key:
nw_idx[idx] = recodes[key]
df.columns = pd.Index(nw_idx)