python - 再向模式添加一个 StructField

标签 python apache-spark pyspark apache-spark-sql

我的 PySpark 数据框具有以下架构:

schema = spark_df.printSchema()

root
 |-- field_1: double (nullable = true)
 |-- field_2: double (nullable = true)
 |-- field_3 (nullable = true)
 |-- field_4: double (nullable = true)
 |-- field_5: double (nullable = true)
 |-- field_6: double (nullable = true)

我想再向架构中添加一个 StructField,因此新架构如下所示:

root
 |-- field_1: double (nullable = true)
 |-- field_1: double (nullable = true)
 |-- field_2: double (nullable = true)
 |-- field_3 (nullable = true)
 |-- field_4: double (nullable = true)
 |-- field_5: double (nullable = true)
 |-- field_6: double (nullable = true)

我知道我可以手动创建一个 new_schema,如下所示:
new_schema = StructType([StructField("field_0", StringType(), True),
                            :
                         StructField("field_6", IntegerType(), True)])

这适用于少量字段,但如果我有数百个字段则无法生成。所以我想知道有没有更优雅的方法来在模式的开头添加一个新字段?谢谢!

最佳答案

您可以复制现有字段并保留:

to_prepend = [StructField("field_0", StringType(), True)] 

StructType(to_prepend + df.schema.fields)

关于python - 再向模式添加一个 StructField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39561272/

相关文章:

python - 何时缓存 DataFrame?

python - dev_appserver.py 说未知运行时 'python38'

hadoop - Spark Hive Context - 带有分区和大写字段名称的 Avro 表

json - NotSerializableException与Spark上的json4s

apache-spark - PySpark 删除所有特殊字符的所有列名中的特殊字符

python - 在 Spark RDD 和/或 Spark DataFrames 中 reshape /透视数据

python - 使用正则表达式匹配字符串(特定字符串组合除外)

python - QAbstractTableModel 和 QComboBox 一起使用

python - 使用 izip 的 Python 递归生成器中的意外行为

count - pyspark:在一个窗口中计数不相同