PySpark-将DF列合并为命名的StructType

Chr*_*s C 1 python database dataframe pyspark

我想将PySpark数据框的多列合并到的一列中StructType

假设我有一个像这样的数据框:

columns = ['id', 'dogs', 'cats']
vals = [(1, 2, 0),(2, 0, 1)]
df = sqlContext.createDataFrame(vals, columns)
Run Code Online (Sandbox Code Playgroud)

我希望得到的数据框类似于此(不是像它实际打印的那样,而是让您了解如果您还不熟悉StructType的意思):

id | animals
1  | dogs=2, cats=0
2  | dogs=0, cats=1
Run Code Online (Sandbox Code Playgroud)

现在,我可以完成以下任务:

StructType(
    [StructField('dogs', IntegerType(), True),
    [StructField('cats', IntegerType(), True)
)
Run Code Online (Sandbox Code Playgroud)

udf然而,在我的结尾,我宁愿只使用一个函数来完成它。如果不存在,我会感到惊讶。

Psi*_*dom 5

如果您需要一map:创建以列名作为键的文字列,然后使用create_mapfunction构造所需的map列:

from pyspark.sql.functions import create_map, lit
new_df = df.select(
    'id', 
     create_map(lit('dogs'), 'dogs', lit('cats'), 'cats').alias('animals')
     #                key  :  val,        key   :   val
)

new_df.show(2, False)
#+---+----------------------+
#|id |animals               |
#+---+----------------------+
#|1  |[dogs -> 2, cats -> 0]|
#|2  |[dogs -> 0, cats -> 1]|
#+---+----------------------+

new_df.printSchema()
#root
# |-- id: long (nullable = true)
# |-- animals: map (nullable = false)
# |    |-- key: string
# |    |-- value: long (valueContainsNull = true)
Run Code Online (Sandbox Code Playgroud)

如果需要struct:使用struct函数:

from pyspark.sql.functions import struct
new_df = df.select('id', struct('dogs', 'cats').alias('animals'))
new_df.show(2, False)
#+---+-------+
#|id |animals|
#+---+-------+
#|1  |[2, 0] |
#|2  |[0, 1] |
#+---+-------+

new_df.printSchema()
#root
# |-- id: long (nullable = true)
# |-- animals: struct (nullable = false)
# |    |-- dogs: long (nullable = true)
# |    |-- cats: long (nullable = true)
Run Code Online (Sandbox Code Playgroud)