在Python中,不需要预先定义对象即可将其传递给函数。

huangapple go评论68阅读模式
英文:

Pass an object to a function in python without pre-defining it

问题

我想要将一个数据框传递给一个函数,而不需要先定义它或包装在函数内部。我目前正在这样做:

def transform_df(df, column, threshold):
    return df[df[column] < threshold]

df = pd.DataFrame({'columnA':[1, 1.5, 2, 3],
                   'columnB':['A', 'B', 'C', 'D']})

df = df.rename(columns={'columnB':'columnC'})

df = transform_df(df, 'columnA', 2)

我想要将df传递给transform_df(),而不需要先定义它。类似这样:

df \
.rename(columns={'columnB':'columnC'}) \
.transform(df, 'columnA', 2)

在R中,我知道你可以使用管道,并在df的位置明确传递.。谢谢。

英文:

I would like to pass a data frame to a function without defining it first or wrapping within the function. I am currently doing


def transform_df(df, column, threshold):
    return df[df[column]&lt;threshold]


df = pd.DataFrame({&#39;columnA&#39;:[1, 1.5, 2, 3],
                   &#39;columnB&#39;:[&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;]})

df = df.rename(columns={&#39;columnB&#39;:&#39;columnC&#39;})

df = transform_df(df, &#39;columnA&#39;, 2)

I would like to pass df into transform_df() without defining it first. So something like

df \
.rename(columns={&#39;columnB&#39;:&#39;columnC&#39;}) \
.transform(df, &#39;columnA&#39;, 2)

In R I am aware you can use piping and pass . explicitly in place of df. Thank you.

答案1

得分: 2

你可以通过以下方式来"扩展" DataFrame 类,添加一个新的成员方法(通常称为"猴子补丁"):

pd.DataFrame.transform_df = transform_df

然后可以使用.调用它,无需传递 df 参数(它会自动作为函数的第一个参数传递):

df = df.rename(columns={'columnB':'columnC'}).transform_df('columnA', 2)
英文:

You can "extend" the DataFrame class with a new member method (commonly called "monkey patching") by doing this:

pd.DataFrame.transform_df = transform_df

and then call it with the . without passing the df param (it's automatically passed as the first arg to the function:

df = df.rename(columns={&#39;columnB&#39;:&#39;columnC&#39;}).transform_df(&#39;columnA&#39;, 2)

huangapple
  • 本文由 发表于 2023年5月17日 19:35:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76271660.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定