gpt4 book ai didi

python-3.x - 数据框列的 Pyspark 并行循环

转载 作者:行者123 更新时间:2023-12-04 15:58:45 24 4
gpt4 key购买 nike

我有一个带有封装列的原始 Dataframe pyspark。我需要在所有列上循环以展开这些列。我不知道名称列,它们可能会改变。所以我需要通用算法。问题是我不能使用经典循环 (for),因为我需要并行代码。

数据示例:

Timestamp | Layers
1456982 | [[1, 2],[3,4]]
1486542 | [[3,5], [5,5]]

在层中,它是一个包含其他列(具有自己的列名)的列。我的目标是拥有这样的东西:

Timestamp | label | number1 | text | value
1456982 | 1 | 2 |3 |4
1486542 | 3 | 5 |5 |5

如何使用 pyspark 函数对列进行循环?

多谢指教

最佳答案

您可以对此使用 reduce 函数。我不知道你想做什么,但假设你想在所有列中加 1:

from functools import reduce
from pyspark.sql import functions as F

def add_1(df, col_name):
return df.withColumn(col_name, F.col(col_name)+1) # using same column name will update column

reduce(add_1, df.columns, df)

编辑:我不确定在不转换 rdd 的情况下解决它。也许这会有所帮助:

from pyspark.sql import Row

flatF = lambda col: [item for item in l for l in col]
df \
.rdd \
.map(row: Row(timestamp=row['timestamp'],
**dict(zip(col_names, flatF(row['layers']))))) \
.toDF()

关于python-3.x - 数据框列的 Pyspark 并行循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51023217/

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