-1

I have a pandas dataframe

a = [0, 1, 2, 3]
b = [2, 3, 4, 5]

df = pd.DataFrame({'col1':a, 'col2':b})

I dont want to use df.name, but i want to print dataframe name df and also can use somewhere like saving csv

print(df + '.csv')

I am expecting

'df.csv'
Manu Sharma
  • 1,593
  • 4
  • 25
  • 48
  • Does this answer your question? [Get the name of a pandas DataFrame](https://stackoverflow.com/questions/31727333/get-the-name-of-a-pandas-dataframe) – Chris Nov 22 '19 at 05:33
  • https://stackoverflow.com/questions/544919/can-i-print-original-variables-name-in-python & https://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python – Alexander Nov 22 '19 at 05:41

2 Answers2

1

I don't think it is possible. Why don't you try using a dictionary instead.

Example

a = [0, 1, 2, 3]
b = [2, 3, 4, 5]

var_map = {'df':pd.DataFrame({'col1':a, 'col2':b})}

# Save all dataframes in dictionary with name
for key in var_map:
    var_map[key].to_csv(key + ".csv")
Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
Reuben
  • 467
  • 3
  • 9
1
  1. You can subclass pandas.DataFrame as explained here. It is a little tricky but possible...

  2. You can add an attribute directly to the instance of DataFrame. Not recommended but possible.

  3. You can also create a class containing a DataFrame and overload the __repr__ and to_csv methods as mentioned below

Here is an example of the 2nd solution

import pandas as pd
df = pd.DataFrame({'col1':a, 'col2':b})
df.myname ='my_super_name'

Here is an example of the 3rd solution

import pandas as pd

class MyDataFrame():
    def __init__(self, _myname, *args, **kwargs):
        self.myname = _myname
        self.df = pd.DataFrame(*args, **kwargs)

    def __repr__(self):
        return self.myname

    def to_csv(self):
        self.df.to_csv(self.myname + '.csv')

a = [0, 1, 2, 3]
b = [2, 3, 4, 5]

df = MyDataFrame('my_data_frame', {'col1':a, 'col2':b})
print(df)
df.to_csv()
Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49