我有一张桌子
test_table
-------------------
key value
'a' 'apple'
'b' 'ball'
'c' null
'd' ''
我需要通过以下方式进行旋转!测试表中不存在
e
和 f
的键
但我希望 e
和 f
出现在数据透视表中,且值不可用
我想旋转 a、b、c、d、e、f,但在这种情况下任何键值都可能丢失
e
和 f
丢失
pivot_table
------------------------------------
a b c d e f
'apple' 'ball' null 'N/A' 'N/A'
我在 PySpark 中尝试了以下操作:
StringType
、StructType
和 StructField
来定义 DataFrame 的架构。from pyspark.sql import SparkSession
from pyspark.sql.types import StringType, StructType, StructField
smpl_data = [('a', 'apple'),
('b', 'ball'),
('c', None),
('d', '')]
smp_schema = StructType([
StructField("key", StringType(), True),
StructField("value", StringType(), True)
])
dilip_test_df = spark.createDataFrame(smpl_data, schema=smp_schema)
additional_data = [('e', None), ('f', None)]
additional_df = spark.createDataFrame(additional_data, schema=smp_schema)
dilip_combined_df = dilip_test_df.union(additional_df)
dilip_pivoted_df = (dilip_combined_df
.groupBy()
.pivot("key", ["a", "b", "c", "d", "e", "f"])
.agg({"value": "first"}))
dilip_pivoted_df = dilip_pivoted_df.na.fill('N/A', subset=['a', 'b', 'd', 'e', 'f'])
dilip_pivoted_df.show(truncate=False)
+-----+----+----+---+---+---+
|a |b |c |d |e |f |
+-----+----+----+---+---+---+
|apple|ball|NULL| |N/A|N/A|
+-----+----+----+---+---+---+