Py学习  »  Python

Python创建一个函数,其中包含一个链

jvqp • 3 年前 • 1249 次点击  

我来自R,我们喜欢管道,这让代码更容易理解,我尽量应用它。然而,我正在尝试创建一个函数,它在一个字符串中执行许多操作。它们单独工作,但当我试图将它们设置为函数的链时,它们不起作用:

def funtest(df, x):
    (
        df
        .replace({x: {'ä': 'ae', 'ö': 'oe', 'ü': 'ue', 'β': 'ss'}}, regex = True, inplace = True)
        .replace({x: '\s{2,}'}, ' ')
        .replace({x: '^\s+'}, ' ')
        .replace({x: '\s+$'}, ' ')
    )
    return df

 funteste(df, 'strings')

enter image description here

谁能告诉我怎么解决这个问题吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133663
 
1249 次点击  
文章 [ 2 ]  |  最新文章 3 年前
scr
Reply   •   1 楼
scr    3 年前

这是您的固定代码:

def funtest(df, x):
    return (
        df
        .replace({x: {'ä': 'ae', 'ö': 'oe', 'ü': 'ue', 'β': 'ss'}}, regex = True)
        .replace({x: '\s{2,}'}, ' ')
        .replace({x: '^\s+'}, ' ')
        .replace({x: '\s+$'}, ' ')
    )

 funteste(df, 'strings')

我做了两件事。

  1. 移除 inplace=True 这会导致代码失败,因为下一个操作是在非类型上运行的。
  2. 更改了返回位置,因为我们不再在原地操作,我们需要返回所有操作的结果。

这对你有好处吗?

Daweo
Reply   •   2 楼
Daweo    3 年前

不设置 inplace=True 对于 pandas.DataFrame.replace 如果你想要一条这样的链条

就地执行操作,不返回任何值。

只需重新分配结果,考虑简单的例子

import pandas as pd
df = pd.DataFrame({'x':['A','B','C','D','E']})
df = df.replace({'x':{'A':'a'}}).replace({'x':{'C':'c'}}).replace({'x':{'E':'e'}})
print(df)

输出

   x
0  a
1  B
2  c
3  D
4  e