0

So I have the following Code. It should export an excelfile but the naming does not work. Though the contents are alright. The file is named "Empty DataFrame Columns: [Column1, Column2] Index: [].xlsx"

It should be named testDF.xlsx. Is there an easy solution?

import pandas as pd

ExportExcelParam = 1;

testDF = pd.DataFrame(columns=['Column1','Column2'], dtype=object)


def ExcelExportDF(Dataframe, ExportExcelParam):
    if ExportExcelParam == 1: 
        Filename = str(Dataframe) + ".xlsx"
        Dataframe.to_excel(Filename)


ExcelExportDF(testDF, ExportExcelParam)
MarK
  • 141
  • 1
  • 1
  • 10
  • 2
    `Filename = "testDF.xlsx"`? What do you think `str(Dataframe)` returns? –  Jun 30 '21 at 14:18
  • 1
    @Mark You cannot just do `str(Dataframe)` to get the name of the `Dataframe`. You might have to iterate through `globals` to get the name – Abdul Niyas P M Jun 30 '21 at 14:20
  • You're not wrong in this case. But I'd like the function to name the excelfile after the given Dataframe name. So not static but based on the argument Dataframe. – MarK Jun 30 '21 at 14:21
  • 1
    An object has absolutely no way to know what name you assigned it. So what part of the dataframe has the name you want? – Mark Ransom Jun 30 '21 at 14:28
  • Thanks, that makes totally sense! – MarK Jun 30 '21 at 14:30

1 Answers1

1

That is because testDF is not a string, it is just a name of your variable. Now that variable contains a DataFrame, so when you use str(), it will try to provide a reasonable string that represents the DataFrame itself.

An easy solution is to pass the name as string in an additional parameter. Yes, it requires to type the name twice, but it is probable the safest and most straight-forward option, unless you can retrieve the name from somehwere else.

def ExcelExportDF(Dataframe, Filename, ExportExcelParam):
    if ExportExcelParam == 1: 
        Dataframe.to_excel(Filename + ".xlsx")


ExcelExportDF(testDF, 'testDF', ExportExcelParam)

Edit: Just saw the comments. If you know what you are doing, maybe this could work.

  • Thanks, this solves the problem. Pass the object _and_ the string. Otherwise iterating through globals should work! – MarK Jun 30 '21 at 14:32