在R中(多亏了magrittr),您现在可以通过%>%
使用功能更强大的管道语法执行操作。这意味着,不是这样编码:
> as.Date("2014-01-01")
> as.character((sqrt(12)^2)
你也可以这样做:
> "2014-01-01" %>% as.Date
> 12 %>% sqrt %>% .^2 %>% as.character
对我来说,这更具可读性,并且扩展到数据框架之外的用例。python语言支持类似的东西吗?
发布于 2015-06-25 06:01:18
管道是Pandas 0.16.2中的新功能。
示例:
import pandas as pd
from sklearn.datasets import load_iris
x = load_iris()
x = pd.DataFrame(x.data, columns=x.feature_names)
def remove_units(df):
df.columns = pd.Index(map(lambda x: x.replace(" (cm)", ""), df.columns))
return df
def length_times_width(df):
df['sepal length*width'] = df['sepal length'] * df['sepal width']
df['petal length*width'] = df['petal length'] * df['petal width']
x.pipe(remove_units).pipe(length_times_width)
x
注意: Pandas版本保留了Python的引用语义。这就是为什么length_times_width
不需要返回值;它就地修改x
。
发布于 2015-02-05 18:48:56
PyToolz [doc]允许任意组合管道,只是它们不是用管道运算符语法定义的。
点击上面的链接获得快速入门。这是一个视频教程:http://pyvideo.org/video/2858/functional-programming-in-python-with-pytoolz
In [1]: from toolz import pipe
In [2]: from math import sqrt
In [3]: pipe(12, sqrt, str)
Out[3]: '3.4641016151377544'
发布于 2017-10-22 15:50:15
如果您只想将其用于个人脚本,则可能需要考虑使用Coconut而不是Python。
Coconut是Python的超集。因此,您可以使用Coconut的管道操作符|>
,而完全忽略Coconut语言的其余部分。
例如:
def addone(x):
x + 1
3 |> addone
编译为
# lots of auto-generated header junk
# Compiled Coconut: -----------------------------------------------------------
def addone(x):
return x + 1
(addone)(3)
https://stackoverflow.com/questions/28252585
复制相似问题