我试图在我的数据集上运行PySpark中的FPGrowth算法。
from pyspark.ml.fpm import FPGrowth
fpGrowth = FPGrowth(itemsCol="name", minSupport=0.5,minConfidence=0.6)
model = fpGrowth.fit(df)
我得到以下错误:
An error occurred while calling o2139.fit.
: java.lang.IllegalArgumentException: requirement failed: The input
column must be ArrayType, but got StringType.
at scala.Predef$.require(Predef.scala:224)
我的数据帧df格式为:
df.show(2)
+---+---------+--------------------+
| id| name| actor|
+---+---------+--------------------+
| 0|['ab,df']| tom|
| 1|['rs,ce']| brad|
+---+---------+--------------------+
only showing top 2 rows
如果“name”列中的数据的格式为:
name
[ab,df]
[rs,ce]
如何将它转换成从StringType到ArrayType的表单
我根据我的RDD生成了数据帧:
rd2=rd.map(lambda x: (x[1], x[0][0] , [x[0][1]]))
rd3 = rd2.map(lambda p:Row(id=int(p[0]),name=str(p[2]),actor=str(p[1])))
df = spark.createDataFrame(rd3)
rd2.take(2):
[(0, 'tom', ['ab,df']), (1, 'brad', ['rs,ce'])]
最佳答案
对数据帧的name
列中的每一行用逗号分隔。例如
from pyspark.sql.functions import pandas_udf, PandasUDFType
@pandas_udf('list', PandasUDFType.SCALAR)
def split_comma(v):
return v[1:-1].split(',')
df.withColumn('name', split_comma(df.name))
或者更好,不要推迟。直接将name设置为列表。
rd2 = rd.map(lambda x: (x[1], x[0][0], x[0][1].split(',')))
rd3 = rd2.map(lambda p:Row(id=int(p[0]), name=p[2], actor=str(p[1])))
关于python - 在PySpark中将StringType转换为ArrayType,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49681837/