我正在尝试标准化(meage = 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.
非常感谢你!
解决方法:
只需使用普通聚合:
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.