在 pyspark DataFrame 中创建某个类型的空数组列

Dav*_*aub 8 python dataframe apache-spark pyspark

我尝试向 df 添加一个包含空字符串数组的列,但最终添加了一列字符串数组。

我试过这个:

import pyspark.sql.functions as F
df = df.withColumn('newCol', F.array([]))
Run Code Online (Sandbox Code Playgroud)

我怎样才能在 pyspark 中做到这一点?

Dav*_*hao 13

另一种实现空数组列的方法:

import pyspark.sql.functions as F
df = df.withColumn('newCol', F.array(F.array()))
Run Code Online (Sandbox Code Playgroud)

因为F.array()默认为字符串类型数组,所以该newCol列将具有 type ArrayType(ArrayType(StringType,false),false)。如果您需要内部数组是字符串以外的其他类型,则可以F.array()直接转换内部数组,如下所示。

import pyspark.sql.functions as F
import pyspark.sql.types as T
int_array_type = T.ArrayType(T.IntegerType())  # "array<integer>" also works
df = df.withColumn('newCol', F.array(F.array().cast(int_array_type)))
Run Code Online (Sandbox Code Playgroud)

在这个例子中,newCol将有一个类型ArrayType(ArrayType(IntegerType,true),false)


mor*_*007 8

这是其中一种方式:

>>> import pyspark.sql.functions as F
>>> myList = [('Alice', 1)]
>>> df = spark.createDataFrame(myList)
>>> df.schema
StructType(List(StructField(_1,StringType,true),StructField(_2,LongType,true)))
>>> df = df.withColumn('temp', F.array()).withColumn("newCol", F.array("temp")).drop("temp")
>>> df.schema
StructType(List(StructField(_1,StringType,true),StructField(_2,LongType,true),StructField(newCol,ArrayType(ArrayType(StringType,false),false),false)))
>>> df
DataFrame[_1: string, _2: bigint, newCol: array<array<string>>]
>>> df.collect()
[Row(_1=u'Alice', _2=1, newCol=[[]])]
Run Code Online (Sandbox Code Playgroud)