Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 接受未知列数的Spark UDF_Python_Apache Spark_Dataframe_Pyspark_User Defined Functions - Fatal编程技术网

Python 接受未知列数的Spark UDF

Python 接受未知列数的Spark UDF,python,apache-spark,dataframe,pyspark,user-defined-functions,Python,Apache Spark,Dataframe,Pyspark,User Defined Functions,我有一个具有不同模式的spark数据帧列表。例如: list_df = [df1, df2, df3, df4] # df1.columns = ['a', 'b'] # df2.columns = ['a', 'b', 'c'] # df3.columns = ['a', 'b', 'c', 'd'] # df4.columns = ['a', 'b', 'c', 'd', 'e'] 现在,我想编写一个单独的udf,它能够对具有不同列数的数据帧列表进行操作 前面有一篇文章介绍了如何使用sca

我有一个具有不同模式的spark数据帧列表。例如:

list_df = [df1, df2, df3, df4]
# df1.columns = ['a', 'b']
# df2.columns = ['a', 'b', 'c']
# df3.columns = ['a', 'b', 'c', 'd']
# df4.columns = ['a', 'b', 'c', 'd', 'e']
现在,我想编写一个单独的udf,它能够对具有不同列数的数据帧列表进行操作

前面有一篇文章介绍了如何使用scala:,其中udf采用一个列数组

但这种方法似乎不适用于python。有什么建议吗


谢谢。

实际上,这种方法在Python中非常有效:

from pyspark.sql.functions import array, udf

df = sc.parallelize([("a", "b", "c", "d")]).toDF()

f = udf(lambda xs: "+".join(xs))

df.select(f("_1")).show()
## +------------+
## |<lambda>(_1)|
## +------------+
## |           a|
## +------------+

df.select(f(array("_1", "_2"))).show()
## +-----------------------+
## |<lambda>(array(_1, _2))|
## +-----------------------+
## |                    a+b|
## +-----------------------+

df.select(f(array("_1", "_2", "_3"))).show()
## +---------------------------+
## |<lambda>(array(_1, _2, _3))|
## +---------------------------+
## |                      a+b+c|
## +---------------------------+

一个相关的问题:是否有方法访问udf中的列名,以便我能够从正确的字段中获取值?谢谢。你可以试试struct。
g = udf(lambda *xs: "+".join(xs))

df.select(g("_1", "_2", "_3", "_4")).show()
## +------------------------+
## |<lambda>(_1, _2, _3, _4)|
## +------------------------+
## |                 a+b+c+d|
## +------------------------+
h = udf(lambda row: "+".join(row.asDict().keys()))

df.select(h(struct("_1", "_2", "_3"))).show()
## +----------------------------+
## |<lambda>(struct(_1, _2, _3))|
## +----------------------------+
## |                    _1+_3+_2|
## +----------------------------+