gpt4 book ai didi

python - 使用 VectorAssembler 计算平均值和最大值

转载 作者:太空宇宙 更新时间:2023-11-04 05:03:18 33 4
gpt4 key购买 nike

我正在使用数据框,例如:

from pyspark.mllib.linalg import Vectors
from pyspark.ml.feature import VectorAssembler


from pyspark.sql.types import *

schema = StructType([
StructField("ClientId", IntegerType(), True),
StructField("m_ant21", IntegerType(), True),
StructField("m_ant22", IntegerType(), True),
StructField("m_ant23", IntegerType(), True),
StructField("m_ant24", IntegerType(), True)
])

df = sqlContext.createDataFrame(
data=[(0, 5, 5, 4, 0),
(1, 23, 13, 17, 99),
(2, 0, 0, 0, 1),
(3, 0, 4, 1, 0),
(4, 2, 1, 30, 10),
(5, 0, 0, 0, 0)],
schema=schema)

我需要计算每行的平均值和最大值,并使用列“m_ant21”、“m_ant22”、“m_ant23”、“m_ant24”。

我正在尝试使用 vectorAssembler:

assembler = VectorAssembler(
inputCols=["m_ant21", "m_ant22", "m_ant23","m_ant24"],
outputCol="muestra")
output = assembler.transform(df)
output.show()

现在,我创建了一个计算平均值的函数,但输入变量是一个名为“dv”的“DenseVector”:

   dv = output.collect()[0].asDict()['muestra']

def mi_media( dv ) :
return float( sum( dv ) / dv.size )


udf_media = udf( mi_media, DoubleType() )
output1 = output.withColumn( "mediaVec", udf_media ( output.muestra ) )
output1.show()

与最大值相同:

def mi_Max( dv ) :
return float(max( dv ) )
udf_max = udf( mi_Max, DoubleType() )
output2 = output.withColumn( "maxVec", udf_max ( output.muestra ) )
output2.show()

问题是output1.show()和output2.show()的错误。只是它不起作用,我不知道代码发生了什么。我究竟做错了什么?请帮助我。

最佳答案

我已经试过了,检查一下,

from pyspark.sql import functions as F

df.show()
+--------+-------+-------+-------+-------+
|ClientId|m_ant21|m_ant22|m_ant23|m_ant24|
+--------+-------+-------+-------+-------+
| 0| 5| 5| 4| 0|
| 1| 23| 13| 17| 99|
| 2| 0| 0| 0| 1|
| 3| 0| 4| 1| 0|
| 4| 2| 1| 30| 10|
| 5| 0| 0| 0| 0|
+--------+-------+-------+-------+-------+

df1 = df.withColumn('mean',sum(df[c] for c in df.columns[1:])/len(df.columns[1:]))
df1 = df1.withColumn('max',F.greatest(*[F.coalesce(df[c],F.lit(0)) for c in df.columns[1:]]))

df1.show()

+--------+-------+-------+-------+-------+-----+---+
|ClientId|m_ant21|m_ant22|m_ant23|m_ant24| mean|max|
+--------+-------+-------+-------+-------+-----+---+
| 0| 5| 5| 4| 0| 3.5| 5|
| 1| 23| 13| 17| 99| 38.0| 99|
| 2| 0| 0| 0| 1| 0.25| 1|
| 3| 0| 4| 1| 0| 1.25| 4|
| 4| 2| 1| 30| 10|10.75| 30|
| 5| 0| 0| 0| 0| 0.0| 0|
+--------+-------+-------+-------+-------+-----+---+

关于python - 使用 VectorAssembler 计算平均值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45149366/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com