Python 3.x Pyspark自定义转换链接
我有一个数据框,需要在其中执行多次清理、重命名等。如何在类/静态和链中实现自定义方法,如下面所示,以处理列/行数据框转换 targetdf=testdf.cols.remove_white_spaces('*').cols.rename('test','test_new')) 我试图遵循decorator作为实现上述目标的基本步骤,但没有成功,因为IDE没有使用属性decorator处理动态方法 您正在寻找Python 3.x Pyspark自定义转换链接,python-3.x,pyspark,Python 3.x,Pyspark,我有一个数据框,需要在其中执行多次清理、重命名等。如何在类/静态和链中实现自定义方法,如下面所示,以处理列/行数据框转换 targetdf=testdf.cols.remove_white_spaces('*').cols.rename('test','test_new')) 我试图遵循decorator作为实现上述目标的基本步骤,但没有成功,因为IDE没有使用属性decorator处理动态方法 您正在寻找pyspark.sql.DataFrame类 不过我还是要提出警告。虽然它有它的用途,但它
pyspark.sql.DataFrame
类
不过我还是要提出警告。虽然它有它的用途,但它可能会混淆您的IDE或更糟的是,混淆阅读您代码的人
最常见的Pyspark技术之一是创建接受数据帧并返回数据帧的函数。这将允许您使用transform()
方法链接这些操作(该方法存在于Spark的Scala API中,但遗憾的是不在Pyspark中,除非您对其进行了修补)
如果您是monkey patching的新手,但尚未使用Pyspark3.x(从11月6日开始预览),您也可以这样做:
df = spark.createDataFrame([
("A", 0),
("B", 1),
("C", 2)],
schema=("K E Y", "cols with sp aces"))
def remove_whitespace(s):
return "".join(_ for _ in s if not _.isspace())
def remove_whitespace_in_colnames(frame):
old_names_to_new = {c: remove_whitespace(c) for c in frame.columns}
return reduce(lambda df, old_new: (
df.withColumnRenamed(old_new[0], old_new[1])),
old_names_to_new.items(),
frame
)
def other_func(df):
return df
def other_function(df):
return df
functions_to_apply = (remove_whitespace_in_colnames, other_function, other_func)
reduce(lambda df, func: func(df),
functions_to_apply,
df)