gpt4 book ai didi

python - pyspark - 使用 ArrayType 列折叠和求和

转载 作者:行者123 更新时间:2023-12-03 23:39:14 41 4
gpt4 key购买 nike

我正在尝试按元素求和,并且我创建了这个虚拟 df。输出应该是 [10,4,4,1]

from pyspark.sql.types import StructType,StructField, StringType, IntegerType, ArrayType
data = [
("James",[1,1,1,1]),
("James",[2,1,1,0]),
("James",[3,1,1,0]),
("James",[4,1,1,0])
]

schema = StructType([ \
StructField("firstname",StringType(),True), \
StructField("scores", ArrayType(IntegerType()), True) \
])

df = spark.createDataFrame(data=data,schema=schema)
posexplode 有效,但我的真实 df 太大,所以我尝试使用折叠,但它给了我一个错误。有任何想法吗?谢谢!
vec_df = df.select("scores")
vec_sums = vec_df.rdd.fold([0]*4, lambda a,b: [x + y for x, y in zip(a, b)])

File "<ipython-input-115-9b470dedcfef>", line 2, in <listcomp>

TypeError: unsupported operand type(s) for +: 'int' and 'list'

最佳答案

您需要在 fold 之前将行的 RDD 映射到列表的 RDD :

vec_sums = vec_df.rdd.map(lambda x: x[0]).fold([0]*4, lambda a,b: [x + y for x, y in zip(a, b)])
为了帮助理解,您可以查看 RDD 的外观。
>>> vec_df.rdd.collect()
[Row(scores=[1, 1, 1, 1]), Row(scores=[2, 1, 1, 0]), Row(scores=[3, 1, 1, 0]), Row(scores=[4, 1, 1, 0])]

>>> vec_df.rdd.map(lambda x: x[0]).collect()
[[1, 1, 1, 1], [2, 1, 1, 0], [3, 1, 1, 0], [4, 1, 1, 0]]
所以你可以想象 vec_df.rdd包含嵌套列表,需要在 fold 之前取消嵌套.

关于python - pyspark - 使用 ArrayType 列折叠和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66989775/

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