将带有压缩列表的新列作为pyspark中的常量值

问题描述 投票:0回答:1

我有payspark数据框,我想添加具有恒定值x的新列,该列为压缩列表:

x = [('1', 'hello'),('2', 'Hi'),('3', 'Hello')]

但是当我运行此代码时:

df = df.withColumn('case', x)

我收到此错误:

AssertionError: col should be Column

如何将结构赋予此列表以处理此错误,我知道我们可以使用Lit函数获取int或字符串值,但对于这种格式,我不知道该怎么做。

pyspark pyspark-sql pyspark-dataframes
1个回答
0
投票

不太清楚想要什么,但可以将string literals中的structs放入array

x = [('1', 'hello'),('2','Hi'),('3', 'Hello')]

df.withColumn("col1",F.array([F.struct(F.lit((str(i[0])+','+str(i[1])))) for i in x]))\
  .show(truncate=False)

+------------------------------+
|col1                          |
+------------------------------+
|[[1,hello], [2,Hi], [3,Hello]]|
|[[1,hello], [2,Hi], [3,Hello]]|
+------------------------------+
© www.soinside.com 2019 - 2024. All rights reserved.