我有一个具有以下结构的 pyspark 数据框。
当前架构:
root
|-- ID
|-- Information
| |-- Name
| |-- Age
| |-- Gender
|-- Description
我想将名字和姓氏添加到 Information.Name
有没有办法在 pyspark 中添加新列以实现多级结构类型?
预期架构:
root
|-- ID
|-- Information
| |-- Name
| | |-- firstName
| | |-- lastName
| |-- Age
| |-- Gender
|-- Description
使用
withField
,这样就可以了:
df=df.withColumn('Information', F.col('Information').withField('Name', F.struct(*[F.col('Information.Name').alias('FName'), F.lit('').alias('LName')])))
之前的架构:
root
|-- Id: string (nullable = true)
|-- Information: struct (nullable = true)
| |-- Name: string (nullable = true)
| |-- Age: integer (nullable = true)
之后的架构:
root
|-- Id: string (nullable = true)
|-- Information: struct (nullable = true)
| |-- Name: struct (nullable = false)
| | |-- FName: string (nullable = true)
| | |-- LName: string (nullable = false)
| |-- Age: integer (nullable = true)
我用Name的当前值初始化了Fname的值,如果需要的话可以使用子字符串。
如果所有名称都遵循以下模式,那么您可以在空格上拆分。
FirstName LastName
带有数据的示例代码。
from pyspark.sql.types import *
import pyspark.sql.functions as sqlf
data = [{
"ID":1,
"Information":{
"Name":"Alice Wonderland",
"Age":20,
"Gender":"Female"
},
"Description":"Test data"
}]
schema = StructType([
StructField("Description", StringType(), True),
StructField("ID", IntegerType(), True),
StructField("Information",
StructType([
StructField("Name", StringType(), True),
StructField("Age", IntegerType(), True),
StructField("Gender", StringType(), True)
]),True)
])
df = spark.createDataFrame(data,schema)
splitName = sqlf.split(df.Information.Name,' ')
df=df.withColumn('Information', sqlf.col('Information')
.withField('Name', sqlf.struct(splitName[0].alias('firstName'), splitName[1].alias('lastName'))))
df.printSchema()
root
|-- Description: string (nullable = true)
|-- ID: integer (nullable = true)
|-- Information: struct (nullable = true)
| |-- Name: struct (nullable = false)
| | |-- firstName: string (nullable = true)
| | |-- lastName: string (nullable = true)
| |-- Age: integer (nullable = true)
| |-- Gender: string (nullable = true)
df.show(truncate=False)
+-----------+---+---------------------------------+
|Description|ID |Information |
+-----------+---+---------------------------------+
|Test data |1 |{{Alice, Wonderland}, 20, Female}|
+-----------+---+---------------------------------+
这更多的是对此的扩展,而不是答案:
我需要类似地插入缺失的列作为结构字段,但无法对代码中的列名称进行硬编码,因为笔记本需要循环运行。主列名称与循环的类别不同,并且某些类别是从不同主列中挑选列。有没有办法修改此代码以根据列的嵌套结构将缺失的列嵌入到数据框中?