pandas使用多级列名称和concat从excel中读取

2024-04-20 09:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个excel,格式如下

Product      Product_type    
ID           ColumnA        ColumnB        Start Date
10              12              14         01/01/2020 

我需要能够将excel读入pandas数据框,并对多级列进行压缩,以便输出

Product_ID     Product_type_ColumnA        ColumnB        Start Date
10              12                            14          01/01/2020 

在某些excel中,顶级列可以是一个或多个。它只需要在其正下方用列名连接即可

例如输入

Product          
ID           ColumnA        ColumnB        Start Date
10    

以及所需的产量

Product_ID      ColumnA        ColumnB        Start Date
10              12              14         01/01/2020 

Tags: 数据idpandasdate格式typeproductexcel
1条回答
网友
1楼 · 发布于 2024-04-20 09:22:24

这不是很优雅,但您可以将其作为常规导入,然后将第一行附加到列名,然后删除第一行:

# Import df (this would be from excel for you)
df = pd.DataFrame([[1,2,3],[4,5,6]], columns = ['ID', '', ''])

# Pick off first row and make into a list
col_names = df.values.tolist()[0]

# Put together the new column names
new_cols = []
for i in range(len(df.columns)):
    new_cols.append(str(df.columns[i]) + '_' + str(col_names[i]))

# Replace the column names
df.columns = new_cols

# Remove the first row of the df
df = df[1:]

相关问题 更多 >