question.it
question.it

Reputation: 2968

How can I get the name of a DataFrame in Python?

I have below python function to export data frame to csv file. I call it using below script

finalExport(dataAllR, sourcePath, header, started)

def finalExport(data, exportPath, header, te):
    print('# USDF: "finalExport" :-')
    exportPath = exportPath + '\\final_py_upload' + data + '.csv'
    data.to_csv(exportPath, columns = header, sep = ',', index = False)
    print('Process done, result file stored in: ', exportPath)
    if te != '': tpe(te)
    return

I want to use name of dataframe i.e dataAllR that I passed while calling function in script:

exportPath = exportPath + '\\final_py_upload' + data + '.csv'
#                                                ^

I want to generate file name as per data frame name.

Please help on this.

Upvotes: 0

Views: 15413

Answers (2)

holdenweb
holdenweb

Reputation: 37023

The fact of the matter is that Python values do not have names, they are bound to names (sometimes - see the second example). When I write

a = "a string"
b = a

what is the name of "a string"? a, or b, or both? Similarly, when I write

lst = ["orange", "banana", "apple"]

what is the name of "apple"? lst[2] isn't a name, it's a reference to an element of a container. This video by Ned Batchelder discusses potential sources of confusion to those still relatively new to Python.

Unfortunately (?) Pandas dataframes do not have a name attribute or anything like it. Given Python's flexibility it would be very easy to define a NamedDataFrame subclass that did maintain such an attribute, though you would then be faced with the question of how to derive those names in the first place.

Upvotes: 3

Chris
Chris

Reputation: 22953

Since Python allows you to assign arbitrary attribute names to objects, you can assign an attribute named name to your dataframe to represent the name of it:

import pandas as pd 
df = pd.DataFrame()
df.name = 'My Data Frame'
print(df.name) # My Data Frame

In your case, after you define a name attribute for dataAllR:

dataAllR.name = 'dataAllR'

You would use:

exportPath = exportPath + '\\final_py_upload' + data.name + '.csv'

Or, even better:

exportPath = f'{exportPath}\\final_py_upload{data.name}.csv'

Upvotes: 9

Related Questions