Bryan
Bryan

Reputation: 6149

programmatically add pandas DataFrame name to columns

This should be a pretty simple question, but I'm looking to programmatically insert the name of a pandas DataFrame into that DataFrame's column names.

Say I have the following DataFrame:

name_of_df = pandas.DataFrame({1: ['a','b','c','d'], 2: [1,2,3,4]})
print name_of_df
        1  2
     0  a  1
     1  b  2
     2  c  3
     3  d  4

I want to have following:

name_of_df = %%some_function%%(name_of_df)

print name_of_df
           name_of_df1  name_of_df2
        0  a            1
        1  b            2
        2  c            3
        3  d            4

..where, as you can see, the name of the DataFrame is programatically inputted into the column names. I know pandas DataFrames don't have a __name__ attribute, so I'm drawing a blank on how to do this.

Please note that I want to do this programatically, so altering the names of the columns with a hardcoded 'name_of_df' string won't work.

Upvotes: 1

Views: 727

Answers (1)

chrisb
chrisb

Reputation: 52236

From the linked question, you can do something like this. Multiple names can point to the same DataFrame, so this will just grab the "first" one.

def first_name(obj):
   return [k for k in globals() if globals()[k] is obj and not k.startswith('_')][0]


In [24]: first_name(name_of_df)
Out[24]: 'name_of_df'

Upvotes: 1

Related Questions