簡體   English   中英

如何找到數組列的平均值,然后從 pyspark dataframe 中的每個元素中減去平均值?

[英]How to find the mean value of a array column and then subtract the mean from each element in a pyspark dataframe?

這是列表:這是 pyspark 中的 dataframe

ID 列表1 清單2
1 [10, 20, 30] [30, 40, 50]
2 [35、65、85] [15、5、45]

這是所需的 output。 計算每個列表的平均值並從列表中的每個元素中減去平均值。 我為此使用 pyspark。

ID 列表1 清單2
1 [10 平均、20 平均、30 平均] [30 平均、40 平均、50 平均]
2 [35 平均、65 平均、85 平均] [15 平均、5 平均、45 平均]

您可以使用aggregate來計算每個列表的平均值,然后在數組列上使用transform函數來減去每個元素的平均值:

from pyspark.sql import functions as F

df1 = df.withColumn("list1_avg", F.expr("aggregate(list1, bigint(0), (acc, x) -> acc + x, acc -> acc / size(list1))")) \
    .withColumn("list2_avg", F.expr("aggregate(list2, bigint(0), (acc, x) -> acc + x, acc -> acc / size(list2))")) \
    .withColumn("list1", F.expr("transform(list1, x -> x - list1_avg)")) \
    .withColumn("list2", F.expr("transform(list2, x -> x - list2_avg)")) \
    .drop("list1_avg", "list2_avg")

df1.show(truncate=False)

#+---+-------------------------------------------------------------+-------------------------------------------------------------+
#|id |list1                                                        |list2                                                        |
#+---+-------------------------------------------------------------+-------------------------------------------------------------+
#|1  |[-10.0, 0.0, 10.0]                                           |[-10.0, 0.0, 10.0]                                           |
#|2  |[-26.666666666666664, 3.3333333333333357, 23.333333333333336]|[-6.666666666666668, -16.666666666666668, 23.333333333333332]|
#+---+-------------------------------------------------------------+-------------------------------------------------------------+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM