创建一个包含一个列表作为数据类型的spark数据框列

时间:2020-10-23 14:11:37

标签: pyspark

我有一个现有的数据框'df',其列为'list_len',我想创建一个由空字符串组成的列,其长度由'list_len'的值指示。

我尝试在pyspark中做df.withColumn('new_list', array(['']*col('list_len'))).show(),但是没有用。

任何想法/帮助都将不胜感激!

+---------+------------------+
|list_len |        new_list  |
+---------+------------------+
|        1|              ['']|
|        3|      ['', '', '']|
|        2|          ['', '']|
+----------------------------+

1 个答案:

答案 0 :(得分:1)

scala:

import org.apache.spark.sql.functions.{lit,array_repeat}
import spark.implicits._

val df = Seq(1, 2, 3).toDF("list_len")
df.withColumn("new_list", array_repeat(lit(""), $"list_len"))

参考: https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/functions.html#array_repeat-org.apache.spark.sql.Column-org.apache.spark.sql.Column-

pyspark:

from pyspark.sql.functions import lit, array_repeat, col
df.withColumn("new_list", array_repeat(lit(""), col("list_len")))

参考:https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.array_repeat