如何使用StandardScaler标准化Spark中的一列?

时间:2017-12-03 22:40:39

标签: python apache-spark pyspark scale

我试图在我的数据框中标准化(mean = 0,std = 1)一列('age')。下面是我在Spark(Python)中的代码:

from pyspark.ml.feature import StandardScaler
from pyspark.ml.feature import VectorAssembler
from pyspark.ml import Pipeline

# Make my 'age' column an assembler type:
age_assembler = VectorAssembler(inputCols= ['age'], outputCol = "age_feature")

# Create a scaler that takes 'age_feature' as an input column:
scaler = StandardScaler(inputCol="age_feature", outputCol="age_scaled",
                        withStd=True, withMean=True)

# Creating a mini-pipeline for those 2 steps:
age_pipeline = Pipeline(stages=[age_assembler, scaler])
scaled = age_pipeline.fit(sample17)
sample17_scaled = scaled.transform(sample17)
type(sample17_scaled)

似乎运行得很好。最后一行产生:“sample17_scaled:pyspark.sql.dataframe.DataFrame”

但是当我运行下面的行时,它显示新列age_scaled的类型为'vector':| - age_scaled:vector(nullable = true)

sample17_scaled.printSchema()

如何使用此新列计算任何内容?例如,我无法计算平均值。当我尝试时,它说它应该是“长”而不是udt。

非常感谢!

1 个答案:

答案 0 :(得分:3)

只需使用普通聚合:

from pyspark.sql.functions import stddev, mean, col

sample17 = spark.createDataFrame([(1, ), (2, ), (3, )]).toDF("age")

(sample17
  .select(mean("age").alias("mean_age"), stddev("age").alias("stddev_age"))
  .crossJoin(sample17)
  .withColumn("age_scaled" , (col("age") - col("mean_age")) / col("stddev_age")))

# +--------+----------+---+----------+
# |mean_age|stddev_age|age|age_scaled|
# +--------+----------+---+----------+
# |     2.0|       1.0|  1|      -1.0|
# |     2.0|       1.0|  2|       0.0|
# |     2.0|       1.0|  3|       1.0|
# +--------+----------+---+----------+

mean_age, sttdev_age = sample17.select(mean("age"), stddev("age")).first()
sample17.withColumn("age_scaled", (col("age") - mean_age) / sttdev_age)

# +---+----------+
# |age|age_scaled|
# +---+----------+
# |  1|      -1.0|
# |  2|       0.0|
# |  3|       1.0|
# +---+----------+

如果您需要Transformer,可以split vector into columns