我有以下功能,我希望能够将它们链接在一起以便使用更清晰的代码:
def label_encoder(dataframe, column):
"""
Encodes categorical variables
"""
le = preprocessing.LabelEncoder()
le.fit(dataframe[column])
dataframe[column] = le.transform(dataframe[column])
return dataframe
def remove_na_and_inf(dataframe):
"""
Removes rows containing NaNs, inf or -inf from dataframes
"""
dataframe.replace([np.inf, -np.inf], np.nan, inplace=True).dropna(how="all", inplace=True)
return dataframe
def create_share_reate_vars(dataframe):
"""
Generate share rate to use as interaction var
"""
for interval in range(300, 3900, 300):
interval = str(interval)
dataframe[interval + '_share_rate'] = dataframe[interval + '_shares'] / dataframe[interval + '_video_views']
return dataframe
def generate_logged_values(dataframe):
"""
Generate logged values for all features which can be logged
"""
columns = list(dataframe.columns)
for feature in columns:
try:
dataframe[str(feature + '_log')] = np.log(dataframe[feature])
except AttributeError:
continue
return dataframe
我想做这样的事情:
new_df = reduce(lambda x, y: y(x), reversed([label_encoder, remove_na_and_inf, create_share_reate_vars, generate_logged_values]), df)
但由于第一个函数有两个参数,因此不起作用。任何解决方案,或者可能是一个完全不同的范例?
答案 0 :(得分:3)
您可以先使用functools.partial部分评估label_encoder
,然后使用该版本解析为lambda。 E.g。
from functools import partial
fixed_col_bound_encoder = partial(label_encoder, column=2)
new_df = reduce(lambda x, y: y(x), reversed([fixed_col_bound_encoder, remove_na_and_inf, create_share_reate_vars, generate_logged_values]), df)