向数据帧添加索引。 Pyspark 2.4.4

时间:2021-02-04 00:31:01

标签: apache-spark pyspark

有很多例子都给出了相同的基本例子。

dfWithIndex = df.withColumn('f_index', \ 
  pyspark.sql.functions.lit(1).cast(pyspark.sql.types.LongType()))
rdd = df.rdd.zipWithIndex().map(lambda row, rowId: (list(row) + [rowId + 1]))
dfIndexed = sqlContext.createDataFrame(rdd, schema=dfWithIndex.schema)

使用这些 lambdas 真的很新,但是使用普通的 zipEithIndex() 打印 rdd 给了我一个两列的数据框.. _1 (struct) 和一个 _2 long 用于索引本身。这就是 lambda 似乎引用的内容。但是我收到此错误:

TypeError: <lambda>() missing 1 required positional argument: 'rowId'

1 个答案:

答案 0 :(得分:1)

你很接近。您只需要稍微修改 lambda 函数。它应该接受 1 个参数,类似于 (Row, id),并返回单个 Row 对象。

from pyspark.sql import Row
from pyspark.sql.types import StructField, LongType

df = spark.createDataFrame([['a'],['b'],['c']],['val'])
df2 = df.rdd.zipWithIndex().map(
    lambda r: Row(*r[0], r[1])
).toDF(df.schema.add(StructField('id', LongType(), False)))

df2.show()
+---+---+
|val| id|
+---+---+
|  a|  0|
|  b|  1|
|  c|  2|
+---+---+