在pyspark中添加新列,并将压缩列表作为常量值
我有payspark dataframe,我想添加具有常量值的新列x,它是压缩列表:在pyspark中添加新列,并将压缩列表作为常量值,pyspark,pyspark-sql,pyspark-dataframes,Pyspark,Pyspark Sql,Pyspark Dataframes,我有payspark dataframe,我想添加具有常量值的新列x,它是压缩列表: x = [('1', 'hello'),('2', 'Hi'),('3', 'Hello')] 但当我运行此代码时: df = df.withColumn('case', x) 我得到这个错误: AssertionError: col should be Column 我如何给这个列表赋予struct来处理这个错误,我知道对于int或string值,我们可以使用Lit函数,但是对于这种格式,我不知道该怎么
x = [('1', 'hello'),('2', 'Hi'),('3', 'Hello')]
但当我运行此代码时:
df = df.withColumn('case', x)
我得到这个错误:
AssertionError: col should be Column
我如何给这个列表赋予struct来处理这个错误,我知道对于int或string值,我们可以使用Lit函数,但是对于这种格式,我不知道该怎么做。你可以将
字符串文本
放入结构
中的数组中
x = [('1', 'hello'),('2','Hi'),('3', 'Hello')]
df.withColumn("col1", F.array(*[F.struct(F.lit(i[0]),F.lit(i[1])) for i in x])).show(truncate=False)
+---------------------------------+
|col1 |
+---------------------------------+
|[[1, hello], [2, Hi], [3, Hello]]|
|[[1, hello], [2, Hi], [3, Hello]]|
+---------------------------------+
或
,您创建了一个数组
的数组
:
x = [('1', 'hello'),('2','Hi'),('3', 'Hello')]
df.withColumn("col1", F.array(*[F.array(F.lit(i[0]),F.lit(i[1])) for i in x])).show(truncate=False)
+---------------------------------+
|col1 |
+---------------------------------+
|[[1, hello], [2, Hi], [3, Hello]]|
|[[1, hello], [2, Hi], [3, Hello]]|
+---------------------------------+
或
,您可以以类似方式使用创建地图
:
x = [('1', 'hello'),('2','Hi'),('3', 'Hello')]
df.withColumn("col1",F.array(*[F.create_map(F.lit(i[0]),F.lit(i[1])) for i in x])).show(truncate=False)
+---------------------------------------+
|col1 |
+---------------------------------------+
|[[1 -> hello], [2 -> Hi], [3 -> Hello]]|
|[[1 -> hello], [2 -> Hi], [3 -> Hello]]|
+---------------------------------------+
它工作得很好,但对于pandas dataframe,我使用此列来应用函数,但在pyspark中它有问题,也许我应该在我的udf中更改输入类型,谢谢您的帮助