Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can __repr__ return a dataframe?

Tags:

python

pandas

Is it possible to make __repr__ in the code below return a dataframe?

The code below will throw

TypeError: __str__ returned non-string (type DataFrame)

because - I guess - __repr__ has to return a string.

Or should I replace __repr__ with some other magic method?

import pandas as pd

class Query():
    def __init__(self, filename):
        self.df = pd.read_excel(filename)
        
    def __repr__(self):
        return self.df
       
if __name__ == '__main__':
    filename = 'some_filename'
    query = Query(filename)
    print(query)
like image 316
barciewicz Avatar asked Jul 28 '26 00:07

barciewicz


1 Answers

You want __repr__ to return a string, which would be the representation of your dataframe. So, just do:

def __repr__(self):
        return repr(self.df)
like image 110
Thierry Lathuille Avatar answered Jul 30 '26 15:07

Thierry Lathuille



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!