Python中文
首页
教程
问答
标签
搜索
登录
注册
使用Python中缀语法从一个函数到另一个函数的“管道”输出
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我试图使用Python/Pandas(作为一个学习练习)大致复制R中的<a href="https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html">dplyr</a>包。我被困在“管道”功能上。</p> <p>在R/dplyr中,这是使用管道运算符<code>%>%</code>完成的,其中<code>x %>% f(y)</code>相当于<code>f(x, y)</code>。如果可能的话,我想使用中缀语法复制它(请参见<a href="http://dev-tricks.net/pipe-infix-syntax-for-python">here</a>)。</p> <p>为了说明这一点,请考虑下面的两个函数。</p> <pre><code>import pandas as pd def select(df, *args): cols = [x for x in args] df = df[cols] return df def rename(df, **kwargs): for name, value in kwargs.items(): df = df.rename(columns={'%s' % name: '%s' % value}) return df </code></pre> <p>第一个函数接受一个dataframe并只返回给定的列。第二个获取数据帧,并重命名给定的列。例如:</p> <pre><code>d = {'one' : [1., 2., 3., 4., 4.], 'two' : [4., 3., 2., 1., 3.]} df = pd.DataFrame(d) # Keep only the 'one' column. df = select(df, 'one') # Rename the 'one' column to 'new_one'. df = rename(df, one = 'new_one') </code></pre> <p>为了使用pipe/infix语法实现相同的功能,代码如下:</p> <pre><code>df = df | select('one') \ | rename(one = 'new_one') </code></pre> <p>所以<code>|</code>左侧的输出作为第一个参数传递给右侧的函数。每当我看到这样的事情完成时(例如,<a href="http://code.activestate.com/recipes/384122-infix-operators/">here</a>),它就涉及lambda函数。是否可以用同样的方式在函数之间传递Pandas的数据帧?</p> <p>我知道Pandas有<code>.pipe</code>方法,但对我来说重要的是我提供的示例的语法。任何帮助都将不胜感激。</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>您可以使用<a href="https://github.com/sspipe/sspipe" rel="nofollow noreferrer">sspipe</a>库,并使用以下语法:</p> <pre><code>from sspipe import p df = df | p(select, 'one') \ | p(rename, one = 'new_one') </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
执行动态python函数以响应httpc
9 回答
执行包含USE statemens的批处理时出现“Invalid cursor state”错误
4 回答
执行包含日志的python脚本时,popen返回错误
3 回答
执行包含来自Linux终端的子进程的Pyqt5GUI会导致GUI中出现黑屏并冻结i
10 回答
执行包含自定义转换器的代码时出现问题?
7 回答
执行半取整
2 回答
执行单元测试时出现Python类型错误
5 回答
执行单击操作,处理当前页面并返回StaleElementReference selenium Python
7 回答
执行单独的、嵌套的if语句是否有效?
3 回答
执行双线性变换的代码不起作用
8 回答
执行反向BWT时,Python列表索引超出范围
8 回答
执行发电机db功能的单元测试
10 回答
执行另一个python脚本并获得输出
9 回答
执行只考虑timeseries数据帧中的上一年的pct\U change()?
2 回答
执行可能不友好的python cod
4 回答
执行各向异性扩散的Python代码,无法在Anacond中运行它
5 回答
执行合并后在dataframe中创建新列
5 回答
执行合并排序时出现逻辑错误
2 回答
执行合并联接列的外部联接
10 回答
执行同一代码时的不同值
6 回答