PySpark: Concatenate Two Columns with Datatype of 'Struc' --> Error: Cannot Resolve Due to Datatype Mismatch

PySpark: Concatenate Two Columns with Datatype of 'Struc' --> Error: Cannot Resolve Due to Datatype Mismatch

我在 PySpark 中有一个数据 table,其中包含数据类型为 'struc' 的两列。

请参阅下面的示例数据框:

word_verb                   word_noun
{_1=cook, _2=VB}            {_1=chicken, _2=NN}
{_1=pack, _2=VBN}           {_1=lunch, _2=NN}
{_1=reconnected, _2=VBN}    {_1=wifi, _2=NN}

我想将两列连接在一起,这样我就可以对连接的动词和名词块进行频率计数。

我试过下面的代码:

df = df.withColumn('word_chunk_final', F.concat(F.col('word_verb'), F.col('word_noun')))  

但我收到以下错误:

AnalysisException: u"cannot resolve 'concat(`word_verb`, `word_noun`)' due to data type mismatch: input to function concat should have been string, binary or array, but it's [struct<_1:string,_2:string>, struct<_1:string,_2:string>]

我想要的输出table如下。连接的新字段的数据类型为字符串:

word_verb                   word_noun               word_chunk_final
{_1=cook, _2=VB}            {_1=chicken, _2=NN}     cook chicken
{_1=pack, _2=VBN}           {_1=lunch, _2=NN}       pack lunch
{_1=reconnected, _2=VBN}    {_1=wifi, _2=NN}        reconnected wifi 

您的代码就快完成了。

假设您的架构如下:

df.printSchema()
#root
# |-- word_verb: struct (nullable = true)
# |    |-- _1: string (nullable = true)
# |    |-- _2: string (nullable = true)
# |-- word_noun: struct (nullable = true)
# |    |-- _1: string (nullable = true)
# |    |-- _2: string (nullable = true)

您只需访问每个列的 _1 字段的值:

import pyspark.sql.functions as F

df.withColumn(
    "word_chunk_final", 
    F.concat_ws(' ', F.col('word_verb')['_1'], F.col('word_noun')['_1'])
).show()
#+-----------------+------------+----------------+
#|        word_verb|   word_noun|word_chunk_final|
#+-----------------+------------+----------------+
#|        [cook,VB]|[chicken,NN]|    cook chicken|
#|       [pack,VBN]|  [lunch,NN]|      pack lunch|
#|[reconnected,VBN]|   [wifi,NN]|reconnected wifi|
#+-----------------+------------+----------------+

此外,您应该使用 concat_ws ("concatenate with separator") 而不是 concat 将字符串添加到一起,并在它们之间添加 space。它类似于 str.join 在 python 中的工作方式。