简体   繁体   中英

Why does changing `__repr__` in a pandas DataFrame not change its display?

Purely pedagogical, not trying to change anything. We have

class A:
    def __init__(self):
        pass
    
    def __repr__(self):
        return "abc"

a = A()
a
> abc

and

class B:
    def __init__(self):
        pass
B.__repr__ = lambda x: "hi"
b = B()
b
> hi

But the following doesn't do anything.

pd.DataFrame.__repr__ = lambda x: "hi"
df = pd.DataFrame({'a': [1,2], 'b': [3,4]})
df
>   a   b
0   1   3
1   2   4

EDIT: this works in a Python REPL, the above was tested in a Jupyter notebook. The next question would be why it doesn't work in Jupyter, but that's a different question.

See if overriding string gives you the result that you want:

class A:
    def __init__(self):
        pass
    
    def __repr__(self):
        return "abc"

    def __str__(self):
        return "abc"

If neither of those don't work then you aren't modifying the class that you think you are.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM