透视当前 DataFrame 列并执行指定的聚合。
Syntax
pivot(pivot_col, values=None)
参数
| 参数 | 类型 | 说明 |
|---|---|---|
pivot_col |
str | 要透视的列的名称。 |
values |
列表,可选 | 将转换为输出 DataFrame中的列的值列表。 如果未提供,Spark 会急切地计算不同的值 pivot_col ,以确定生成的架构。 提供显式列表可避免这种预先计算。 |
退货
GroupedData
示例
from pyspark.sql import Row, functions as sf
df1 = spark.createDataFrame([
Row(course="dotNET", year=2012, earnings=10000),
Row(course="Java", year=2012, earnings=20000),
Row(course="dotNET", year=2012, earnings=5000),
Row(course="dotNET", year=2013, earnings=48000),
Row(course="Java", year=2013, earnings=30000),
])
# Compute the sum of earnings for each year by course with each course as a separate column.
df1.groupBy("year").pivot("course", ["dotNET", "Java"]).sum("earnings").sort("year").show()
# +----+------+-----+
# |year|dotNET| Java|
# +----+------+-----+
# |2012| 15000|20000|
# |2013| 48000|30000|
# +----+------+-----+
# Without specifying column values (less efficient).
df1.groupBy("year").pivot("course").sum("earnings").sort("year").show()
# +----+-----+------+
# |year| Java|dotNET|
# +----+-----+------+
# |2012|20000| 15000|
# |2013|30000| 48000|
# +----+-----+------+
# Using a nested column as the pivot column.
df2 = spark.createDataFrame([
Row(training="expert", sales=Row(course="dotNET", year=2012, earnings=10000)),
Row(training="junior", sales=Row(course="Java", year=2012, earnings=20000)),
Row(training="expert", sales=Row(course="dotNET", year=2012, earnings=5000)),
Row(training="junior", sales=Row(course="dotNET", year=2013, earnings=48000)),
Row(training="expert", sales=Row(course="Java", year=2013, earnings=30000)),
])
df2.groupBy("sales.year").pivot("sales.course").agg(sf.sum("sales.earnings")).sort("year").show()
# +----+-----+------+
# |year| Java|dotNET|
# +----+-----+------+
# |2012|20000| 15000|
# |2013|30000| 48000|
# +----+-----+------+