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
438 views
in Technique[技术] by (71.8m points)

python - Pandas to Excel (Merged Header Column)

I want to convert my df to an excel sheet, but also want to add a header column to categorize all the columns. Here is a screenshot without the merged column header

and the second picture shows the 'Financials' and 'Obs' headings

For reproduction:

import pandas as pd
 # Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Close the Pandas Excel writer and output the Excel file.
writer.save()
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can create MultiIndex:

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})

Specified new name of level with start and end column name:

L = [('OBS','A','C'), ('FIN', 'D','F')]

And then in list comprehension create tuples for MultiIndex.from_tuples:

cols = [(new, c) for new, start, end in L for c in df.loc[:, start:end].columns]

print (cols)
[('OBS', 'A'), ('OBS', 'B'), ('OBS', 'C'), ('FIN', 'D'), ('FIN', 'E'), ('FIN', 'F')]

df.columns = pd.MultiIndex.from_tuples(cols)
print (df)
  OBS       FIN      
    A  B  C   D  E  F
0   a  4  7   1  5  a
1   b  5  8   3  3  a
2   c  4  9   5  6  a
3   d  5  4   7  9  b
4   e  5  2   1  2  b
5   f  4  3   0  4  b

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

...