让pandas的.to_clipboard()方法返回原DataFrame或Series (猴子补丁)


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() 结果的同时画出数据图,以便后续处理。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值