I have the below pandas dataframe:
data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, 21, 19, 18]}
df = pd.DataFrame(data)
How can I save each column as a separate sheet in one excel file. So, the excel file would consist of two sheets. I am looking for a general code which can be applied to other dataframes with many number of columns as well. I assume a for loop can resolve this issue.
CodePudding user response:
You can do this:
data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, 21, 19, 18]}
df = pd.DataFrame(data)
with pd.ExcelWriter('output.xlsx') as writer:
for col in df.columns:
df[col].to_excel(writer, sheet_name=col, index=False)
df.columns is a list of column names
sheet_name = column name