Pandas 有一個非常好的功能,可以將 df 保存到剪貼板。這有助于獲取 df 輸出并在 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)
但是,我不想df.to_clipboard(excel=True,index=False)每次需要將 df 復制到剪貼板時都輸入。有沒有辦法我可以做類似的事情df.clip()
我試影像這樣實作它,但它不起作用。
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)
uj5u.com熱心網友回復:
我會打補丁pandas.DataFrame而不是定義子類:
# 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()
剪貼板內容:
A B C
x 1 a
y 2 b
x 2 a
z 2 d
y 2 d
使用模塊
expand_pandas.py
import pandas as pd
# define a function and monkey patch pandas.DataFrame
def clipxl(self):
return self.to_clipboard(excel=True,index=False)
def hello(self):
return 'Hello World!'
pd.DataFrame.clip = clipxl
pd.DataFrame.hello = hello
在您的環境中:
import pandas as pd
import expand_pandas
df = pd.DataFrame({'A': ['x','y','x','z','y'],
'B': [1,2,2,2,2],
'C': ['a','b','a','d','d']})
df.hello()
# 'Hello World!'
df.clip()
# sends to clipboard
uj5u.com熱心網友回復:
您可以撰寫一個函式來代替面向物件的方法,并將 DataFrame 作為引數傳遞。
或者,您可以創建一個包含資料框的類并定義一個執行您想要的方法,而不是修改 DataFrame 類本身。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/506822.html
下一篇:CLSID_FileOpenDialog它在注冊表中的什么位置?是comdlg32嗎?ICommDlg瀏覽器?開放?或者是其他東西?
