gpt4 book ai didi

python - Spark : equivelant of zipwithindex in dataframe

转载 作者:太空狗 更新时间:2023-10-30 01:32:45 28 4
gpt4 key购买 nike

假设我有以下数据框:

dummy_data = [('a',1),('b',25),('c',3),('d',8),('e',1)]
df = sc.parallelize(dummy_data).toDF(['letter','number'])

我想创建以下数据框:

[('a',0),('b',2),('c',1),('d',3),('e',0)]

我所做的是将其转换为 rdd 并使用 zipWithIndex 函数,然后加入结果:

convertDF = (df.select('number')
.distinct()
.rdd
.zipWithIndex()
.map(lambda x:(x[0].number,x[1]))
.toDF(['old','new']))


finalDF = (df
.join(convertDF,df.number == convertDF.old)
.select(df.letter,convertDF.new))

dataframes中是否有类似zipWIthIndex的功能?是否有另一种更有效的方法来完成这项任务?

最佳答案

请查看https://issues.apache.org/jira/browse/SPARK-23074对于数据帧中的这种直接功能奇偶校验..如果你有兴趣在 Spark 的某个时候看到这个,请投票给那个 jira。

这是 PySpark 中的解决方法:

def dfZipWithIndex (df, offset=1, colName="rowId"):
'''
Enumerates dataframe rows is native order, like rdd.ZipWithIndex(), but on a dataframe
and preserves a schema

:param df: source dataframe
:param offset: adjustment to zipWithIndex()'s index
:param colName: name of the index column
'''

new_schema = StructType(
[StructField(colName,LongType(),True)] # new added field in front
+ df.schema.fields # previous schema
)

zipped_rdd = df.rdd.zipWithIndex()

new_rdd = zipped_rdd.map(lambda args: ([args[1] + offset] + list(args[0])))

return spark.createDataFrame(new_rdd, new_schema)

这也可以在 abalon 中找到包。

关于python - Spark : equivelant of zipwithindex in dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39057766/

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