-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'
2

2 Answers 2

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")
Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.