Pandas 中的 DataFrame 和 Series 都有 .to_clipboard()
方法,返回值为 None
。可以通过装饰器给这个方法打猴子补丁,让它的返回值为原DataFrame 或 Series:
import pandas as pd
# MONKEY PATCHING: make pd.DataFrame.to_clipboard return the DataFrame
def return_dataframe_on_clipboard(fn):
def wrapper(*args, **kwargs):
fn(*args, **kwargs)
return args[0]
return wrapper
# Apply the decorator to the original DataFrame.to_clipboard method
pd.core.generic.NDFrame.to_clipboard = return_dataframe_on_clipboard(pd.core.generic.NDFrame.to_clipboard)
尝试一下:
# Example usage
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
print(df)
# Chaining calls and using the modified to_clipboard method
copied_df = df.to_clipboard().head(2)
print(copied_df)
输出结果:
A B
0 1 4
1 2 5
2 3 6
A B
0 1 4
1 2 5
这个补丁在某些场景下很好用,比如用链式方法处理 DataFrame 后,得到处理结果的同时并画图:
import matplotlib.pyplot as plt
# Example usage 2
data = {'gender': [1, 1, 0, 1, 0], 'data': [20, 23, 21.5, 17, 18]}
df = pd.DataFrame(data)
# groupby gender and get mean of data using chaining method
(df.groupby('gender')['data']
.mean()
.to_clipboard()
.plot(kind='bar'))
plt.show()
这样我们在剪贴板得到 groupby()
结果的同时画出数据图,以便后续处理。