Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

python - pandas read from excel with multilevel columnnames and concat

I have an excel with the following format

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

I need to be able to read the excel into a pandas dataframe and concat the multilevel columns so the output is

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

in some excel the top level columns could be one or more. It only needs to concat with the column name directly below it.

for example input

Product          
ID           ColumnA        ColumnB        Start Date
10    

and required output

Product_ID      ColumnA        ColumnB        Start Date
10              12              14         01/01/2020 
question from:https://stackoverflow.com/questions/65887092/pandas-read-from-excel-with-multilevel-columnnames-and-concat

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This isn't very elegant but you could just import it as normal, then append the first row to the column names, then delete the first row:

# 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:]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...