我有一个现有的数据框'df',其列为'list_len',我想创建一个由空字符串组成的列,其长度由'list_len'的值指示。
我尝试在pyspark中做df.withColumn('new_list', array(['']*col('list_len'))).show()
,但是没有用。
任何想法/帮助都将不胜感激!
+---------+------------------+
|list_len | new_list |
+---------+------------------+
| 1| ['']|
| 3| ['', '', '']|
| 2| ['', '']|
+----------------------------+
答案 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"))
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