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
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"')
Comments
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