Apache spark PySpark中的串联列表
在我的Spark数据框中,其中一列是字符串Apache spark PySpark中的串联列表,apache-spark,Apache Spark,在我的Spark数据框中,其中一列是字符串 Activities "1 1 1 1 0 0 0 0 0" "0 0 0 1 1 1 0 0 0" "1 1 1 1 0 0 0 0 0" "0 0 0 1 1 1 0 0 0" "1 1 1 1 0 0 0 0 0" "0 0 0 1 1 1 0 0 0" 我希望从该列的每一行收集字符串,并通过串联形成一个列表。然后,拆分这个巨大的字符串,生成一个巨大的单整数数组,如 [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1,
Activities
"1 1 1 1 0 0 0 0 0"
"0 0 0 1 1 1 0 0 0"
"1 1 1 1 0 0 0 0 0"
"0 0 0 1 1 1 0 0 0"
"1 1 1 1 0 0 0 0 0"
"0 0 0 1 1 1 0 0 0"
我希望从该列的每一行收集字符串,并通过串联形成一个列表。然后,拆分这个巨大的字符串,生成一个巨大的单整数数组,如
[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0,...]
(当然,可以先将字符串拆分为列表,然后附加所有列表以形成一个大列表,但如何连接基于RDD的列表的问题仍然存在)
使用pythons本地数据结构,我可以做到:
import pyspark.sql.functions as F
allActivities = []
activitiesListColumn = df.agg(F.collect_list("Activities").alias("Activities")).collect()[0]
for rowActivity in activitiesListColumn["Activities"]:
activities = rowActivity.split()
allActivities += activities
print(allActivities)
如何使用基于RDD(即并行化)的数据结构来实现这一点?这可以通过GROUP_CONCAT方法实现,但spark sql不包含此方法。我们可以确定一个像GROUP_CONCAT一样运行的UDF。关于此UDF的详细信息,请参见此链接:。。但是我们必须将分隔符(“,”改为“”)。。然后,你可以试试这句话:
df.agg(GroupConcat(new ColumnName("your_string_array"))).show
GroupConcat对象是:
object GroupConcat extends UserDefinedAggregateFunction {
def inputSchema = new StructType().add("x", StringType)
def bufferSchema = new StructType().add("buff", ArrayType(StringType))
def dataType = StringType
def deterministic = true
def initialize(buffer: MutableAggregationBuffer) = {
buffer.update(0, ArrayBuffer.empty[String])
}
def update(buffer: MutableAggregationBuffer, input: Row) = {
if (!input.isNullAt(0))
buffer.update(0, buffer.getSeq[String](0) :+ input.getString(0))
}
def merge(buffer1: MutableAggregationBuffer, buffer2: Row) = {
buffer1.update(0, buffer1.getSeq[String](0) ++ buffer2.getSeq[String](0))
}
def evaluate(buffer: Row) = UTF8String.fromString(
buffer.getSeq[String](0).mkString(" "))
}
类似这样的东西:rdd.map(lambda x:list(map(int,x.split('),'))