3

I am trying to write specific columns of the data frame to an excel sheet. My data frame has 3 columns and I only want to write one of those columns to a new sheet. I know this can be done in CSV bypassing columns but what about excel?

2 Answers 2

5

Say for example, you have dataframe with 3 columns whose column names are "animals","column_1", "column_2". If you need only column_1 and column_2 to be exported as xlsx file, you can do as shown below,

df = pd.DataFrame(data=[['dog','a','b'],['cat','b','c'],['dog','c','a']],columns=(['animal','column1','column2']))
df[['column1','column2']].to_excel('"output.xlsx"')
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the "to_excel" function from pandas.

Given your dataframe "dt1":

dt1.to_excel("ExcelFile.xlsx",columns=['col1', 'col3'], sheet_name = "NewSheet1")

If you have a existing excel file you can add those columns to a new sheet with an ExcelWriter:

with pd.ExcelWriter('ExcelFile.xlsx', mode = 'a') as excel_writer:
  dt1.to_excel(excel_writer, columns=['col1', 'col3'], sheet_name = "NewSheet1")

There is more examples at the pandas documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.