博客
关于我
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/

你可能感兴趣的文章
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
org.apache.http.conn.HttpHostConnectException: Connection to refused
查看>>
org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>