현재 DataFrame 열을 피벗하고 지정된 집계를 수행합니다.
문법
pivot(pivot_col, values=None)
매개 변수
| 매개 변수 | 유형 | 설명 |
|---|---|---|
pivot_col |
str | 피벗할 열의 이름입니다. |
values |
list, optional | 출력 DataFrame의 열로 변환될 값 목록입니다. 제공되지 않은 경우 Spark는 고유 값을 pivot_col 열심히 계산하여 결과 스키마를 확인합니다. 명시적 목록을 제공하면 이러한 즉시 계산을 방지할 수 있습니다. |
Returns
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|
# +----+-----+------+