删除多索引和自动重命名列

时间:2016-08-23 04:39:52

标签: python pandas dataframe group-by multi-index

我想将以下输出转换为:

  • 删除多索引(它应该只是一行索引)

  • 相应编号工作1,工作生效日期1,工作2,工作生效日期2等

  • 如果我选择添加或删除其他变量,我希望这是可扩展的,我不想修改代码以适应它(这是示例缩小)。

部分数据:

import pandas as pd
import numpy as np

data1 = {'Name': ["Joe", "Joe", "Joe","Jane","Jane"],
        'Job': ["Analyst","Manager","Director","Analyst","Manager"],
        'Job Eff Date': ["1/1/2015","1/1/2016","7/1/2016","1/1/2015","1/1/2016"]}
df2 = pd.DataFrame(data1, columns=['Name', 'Job', 'Job Eff Date'])

def tgrp(df):
    df = df.drop('Name', axis=1)
    return df.reset_index(drop=True).T

df2.groupby('Name').apply(tgrp).unstack()

enter image description here

2 个答案:

答案 0 :(得分:5)

尝试:

df3.columns = ['{} {}'.format(col[1], col[0]) for col in df3.columns]

如果你可以使用基于0的索引。否则更改为col[0] + 1

答案 1 :(得分:4)

join的另一种解决方案:

df.columns = [' '.join((col[1], str(col[0] + 1))) for col in df.columns]
print (df)
        Job 1 Job Eff Date 1    Job 2 Job Eff Date 2     Job 3 Job Eff Date 3
Name                                                                         
Jane  Analyst       1/1/2015  Manager       1/1/2016       NaN            NaN
Joe   Analyst       1/1/2015  Manager       1/1/2016  Director       7/1/2016

如果需要删除索引名称,请使用rename_axispandas 0.18.0中的新内容):

df.columns = [' '.join((col[1], str(col[0] + 1))) for col in df.columns]
df = df.rename_axis(None)
print (df)
        Job 1 Job Eff Date 1    Job 2 Job Eff Date 2     Job 3 Job Eff Date 3
Jane  Analyst       1/1/2015  Manager       1/1/2016       NaN            NaN
Joe   Analyst       1/1/2015  Manager       1/1/2016  Director       7/1/2016

工作原理:

列表理解将MultiIndex转换为list tuples,由join加入,但首先必须添加1并转换int每个第一个元组项的str

print ([col for col in df.columns])
[(0, 'Job'), (0, 'Job Eff Date'), 
 (1, 'Job'), (1, 'Job Eff Date'), 
 (2, 'Job'), (2, 'Job Eff Date')]

输出是字符串列表,分配给列名:

print ([' '.join((col[1], str(col[0] + 1))) for col in df.columns])
['Job 1', 'Job Eff Date 1', 'Job 2', 'Job Eff Date 2', 'Job 3', 'Job Eff Date 3']