我在更大的堆叠数据集上尝试了1.6的新“数据透视”功能。它有5,656,458行,IndicatorCode
列有1344个不同的代码。
想法是使用数据透视来“拆栈”(以熊猫为单位)该数据集,并为每个IndicatorCode设置一列。
schema = StructType([ \
StructField("CountryName", StringType(), True), \
StructField("CountryCode", StringType(), True), \
StructField("IndicatorName", StringType(), True), \
StructField("IndicatorCode", StringType(), True), \
StructField("Year", IntegerType(), True), \
StructField("Value", DoubleType(), True) \
])
data = sqlContext.read.load('hdfs://localhost:9000/tmp/world-development-indicators/Indicators.csv',
format='com.databricks.spark.csv',
header='true',
schema=schema)
data2 = indicators_csv.withColumn("IndicatorCode2", regexp_replace("indicatorCode", "\.", "_"))\
.select(["CountryCode", "IndicatorCode2", "Year", "Value"])
columns = [row.IndicatorCode2 for row in data2.select("IndicatorCode2").distinct().collect()]
data3 = data2.groupBy(["Year", "CountryCode"])\
.pivot("IndicatorCode2", columns)\
.max("Value")
尽管此操作成功返回,但data3.first()
从未返回结果(10分钟后,我使用3个内核在独立服务器上中断了此操作)。
我的方法使用得很好,RDD
并且aggregateByKey
效果很好,所以我不是在寻找解决方案,而是使用DataFrames枢轴也可以解决问题。
好吧,通常来说,数据透视不是一个非常有效的操作,并且使用DataFrame
API可以做的事情很少。您可以尝试的一件事是repartition
数据:
(data2
.repartition("Year", "CountryCode")
.groupBy("Year", "CountryCode")
.pivot("IndicatorCode2", columns)
.max("Value"))
甚至合计:
from pyspark.sql.functions import max
(df
.groupBy("Year", "CountryCode", "IndicatorCode")
.agg(max("Value").alias("Value"))
.groupBy("Year", "CountryCode")
.pivot("IndicatorCode", columns)
.max("Value"))
申请前pivot
。两种解决方案背后的想法是相同的。而不是移动大扩展,而是Rows
移动狭窄的密集数据并在本地扩展。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句