Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

implement shortcut for pandas code by extending it

Pandas has a very nice feature to save a df to clipboard. This help a lot to take the df output and analyze/inspect further in excel.

 df={'A':['x','y','x','z','y'],
                   'B':[1,2,2,2,2],
                   'C':['a','b','a','d','d']}
df=pd.DataFrame(df)
df.to_clipboard(excel=True,index=False)

However I don’t want to type df.to_clipboard(excel=True,index=False) each time I need to copy the df to clipboard. Is there a way I can do something like df.clip()

I tried to implement it like this but it does not work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class ExtDF(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super(ExtDF,  self).__init__(*args, **kwargs)

    @property
    def _constructor(self):
        return ExtDF
    def clip(self):
        return self.to_clipboard(excel=True,index=False)

>Solution :

I would monkey patch pandas.DataFrame rather than defining a subclass:

# define a function and monkey patch pandas.DataFrame
def clipxl(self):
    return self.to_clipboard(excel=True, index=False)

pd.DataFrame.clip = clipxl

# now let's try it
df={'A': ['x','y','x','z','y'],
    'B': [1,2,2,2,2],
    'C': ['a','b','a','d','d']}
df=pd.DataFrame(df)
df.clip()

clipboard content:

A   B   C
x   1   a
y   2   b
x   2   a
z   2   d
y   2   d
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading