使用多行作为熊猫的列标题

时间:2019-05-30 16:33:47

标签: python pandas header multi-index

我有一个导入的数据框,如下所示。

df = pd.read_excel("./Data.xlsx", sheet_name="Customer Care", header=None)

我想将前三行设置为列标题,但不知道如何执行此操作。我尝试了以下方法:

df.columns = df.iloc[0:3,:]

但这似乎不起作用。

我在this答案中看到了类似的内容。但这仅适用于所有子列都将以相同的方式命名的情况,不一定是这种情况。

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:4)

df = pd.read_excel(
    "./Data.xlsx", 
    sheet_name="Customer Care", 
    header=[0,1,2]
)

这将告诉熊猫读取Excel文件的前三行作为多索引列标签。

如果要在加载后修改行,则将其设置为列

#set the first three rows as columns
df.columns=pd.MultiIndex.from_arrays(df.iloc[0:3].values)
#delete the first three rows (because they are also the columns
df=df.iloc[3:]