[英]How can I pass function as argument with parameter in python pandas pipe
I wanna make some function to use pipe of pandas.我想制作一些使用熊猫管道的功能。
Like this像这样
import pandas as pd
def foo(df):
df['A'] = 1
return df
def goo(df):
df['B'] = 2
return df
def hoo(df, arg1):
df[arg1] = 3
return df
df = pd.DataFrame.from_dict({"A":[1, 2, 3],
"B":[4, 5, 6]})
print(df)
(df.pipe(foo)
.pipe(goo)
.pipe(hoo, arg1='Hello')
)
print(df)
The first print is第一张印刷品是
A B
0 1 4
1 2 5
2 3 6
The second ptint is第二个点是
A B Hello
0 1 2 3
1 1 2 3
2 1 2 3
It is meaningless code and easy to understand.这是无意义的代码,易于理解。
There are many combination of function sch as foo, goo, hoo.函数 sch 有许多组合,如 foo、goo、hoo。 I need to abstract this pipe code.我需要抽象这个管道代码。
import pandas as pd
def foo(df):
df['A'] += 1
return df
def goo(df):
df['B'] += 2
return df
def hoo(df, arg1):
df[arg1] = 3
return df
def pipe_line(df, func_list, kargs_list):
for func, kargs in zip(func_list, kargs_list):
df = func(df, **kargs)
return df
df = pd.DataFrame.from_dict({"A":[1, 2, 3],
"B":[4, 5, 6]})
df = pipe_line(df,
[foo, goo, hoo],
[{}, {}, dict(arg1="HELLO")])
print(df)
But, pipe_line function is very ugly.但是, pipe_line函数非常难看。 How can I upgrade readability of this function?如何升级此功能的可读性?
pipe_line
doesn't really have to much at all: just repeatedly apply functions to the return values of previous functions until you are out of functions. pipe_line
根本不需要太多:只需重复将函数应用于先前函数的返回值,直到函数用完。
def pipe_line(df, fs):
for f in fs:
df = f(df)
return df
The trick is to define appropriate functions that all take a single dataframe argument.诀窍是定义适当的函数,它们都采用单个数据帧参数。 functools.partial
helps with that. functools.partial
对此有所帮助。
from functools import partial
df = pipeline(df, [foo, goo, partial(hoo, arg1="HELLO")])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.