我正在编写一个从recode
字典重新编码Pandas DataFrame索引对象的函数。
recodes = {'sales' : 'CurrentSales', 'cash' : 'US$' }
使用示例:
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)
我实施的内容基本上是:
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)
答案 0 :(得分:3)
df.rename(columns={'sales' : 'CurrentSales', 'cash' : 'US$' })