英文:
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]<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)
I would like to pass df
into transform_df()
without defining it first. So something like
df \
.rename(columns={'columnB':'columnC'}) \
.transform(df, 'columnA', 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={'columnB':'columnC'}).transform_df('columnA', 2)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论