博客
关于我
python_链式编程技术_管道技术
阅读量:386 次
发布时间:2019-03-05

本文共 1004 字,大约阅读时间需要 3 分钟。

链式编程技术与管道技术

在处理数据集时,经常会发现多次变换后产生的临时变量实际上并未在分析中使用。例如:

df = load_data()df2 = df[df['col2'] < 0]df2['col1_demeaned'] = df2['col1'] - df2['col1'].mean()result = df2.groupby('key').col1_demeaned.std()

虽然这段代码没有使用真实数据,但它揭示了一些新的方法。首先,DataFrame.assign 是一种类似 df[k] = v 的函数式方法,可以用来对 DataFrame 进行列赋值。它的使用方式是返回修改后的新 DataFrame,而不是在原 DataFrame 上进行修改。因此,以下两种写法是等价的:

# 常规非函数式写法df2 = df.copy()df2['k'] = v# 函数式写法df2 = df.assign(k=v)

在链式编程中,需要注意临时对象的使用。例如:

df = load_data()result = (df          .pipe(f, arg1=v1)          .pipe(g, v2, arg3=v3)          .pipe(h, arg4=v4))

df.pipe(f)f(df) 是等价的,但 pipe 方法使链式编程更加便捷。此外,pipe 也可以接受类似函数的参数,即可调用的对象(callable),这对于复用操作非常有用。

在处理分组数据时,以下方法可以有效地将操作转换为可复用的函数:

def group_demean(df, by, cols):    result = df.copy()    g = df.groupby(by)    for c in cols:        result[c] = df[c] - g[c].transform('mean')    return result

可以通过以下方式使用:

result = (df          .pipe(group_demean, ['key1', 'key2'], ['col1'])          .groupby('key')          .col1_demeaned.std())

通过这种方式,链式编程使得数据转换更加灵活和可读。

转载地址:http://fnrg.baihongyu.com/

你可能感兴趣的文章
Prometheus 采集器使用详解
查看>>
Prometheus 黑盒监控实战
查看>>
prometheus+alertmanager+grafana监控部署教程
查看>>
Prometheus+Grafana构建智能化Kubernetes监控系统实战
查看>>
Prometheus+SpringBoot应用监控全过程详解
查看>>
Prometheus+SpringBoot应用监控全过程详解
查看>>
prometheus安装
查看>>
Prometheus实战教程:监控Kafka消息
查看>>
Prometheus实战教程:监控mysql数据库
查看>>
Prometheus实战教程:监控Nginx状态
查看>>
prometheus常用exporter下载地址大全
查看>>
Prometheus快速搭建与监控Linux系统实战
查看>>
prometheus报警与恢复告警的格式
查看>>
Pytorch中安装 torch_geometric 详细图文操作(全)
查看>>
prometheus监控docker容器实战
查看>>
Prometheus监控k8s集群使用邮箱和微信告警!
查看>>
Prometheus监控mysq数据库实战
查看>>
prometheus监控nginx实战
查看>>
Prometheus监控redis数据库实战
查看>>
Prometheus监控教程:使用Grafana展示主机基本信息
查看>>