如何在pySpark数据帧中添加Row id

ank*_*tel 17 python apache-spark apache-spark-sql pyspark spark-dataframe

我有一个csv文件; 我在pyspark中转换为DataFrame(df); 经过一番改造; 我想在df中添加一列; 这应该是简单的行id(从0或1开始到N).

我在rdd中转换了df并使用"zipwithindex".我将生成的rdd转换回df.这种方法有效,但它产生了250k的任务,并且需要花费大量的时间来执行.我想知道是否还有其他方法可以减少运行时间.

以下是我的代码片段; 我正在处理的csv文件很大; 包含数十亿行.

debug_csv_rdd = (sc.textFile("debug.csv")
  .filter(lambda x: x.find('header') == -1)
  .map(lambda x : x.replace("NULL","0")).map(lambda p: p.split(','))
  .map(lambda x:Row(c1=int(x[0]),c2=int(x[1]),c3=int(x[2]),c4=int(x[3]))))

debug_csv_df = sqlContext.createDataFrame(debug_csv_rdd)
debug_csv_df.registerTempTable("debug_csv_table")
sqlContext.cacheTable("debug_csv_table")

r0 = sqlContext.sql("SELECT c2 FROM debug_csv_table WHERE c1 = 'str'")
r0.registerTempTable("r0_table")

r0_1 = (r0.flatMap(lambda x:x)
    .zipWithIndex()
    .map(lambda x: Row(c1=x[0],id=int(x[1]))))

r0_df=sqlContext.createDataFrame(r0_2)
r0_df.show(10) 
Run Code Online (Sandbox Code Playgroud)

小智 55

您也可以使用sql包中的函数.它将生成一个唯一的id,但它不会是顺序的,因为它取决于分区的数量.我相信它可以在Spark 1.5 +中使用

from pyspark.sql.functions import monotonicallyIncreasingId

# This will return a new DF with all the columns + id
res = df.withColumn("id", monotonicallyIncreasingId())
Run Code Online (Sandbox Code Playgroud)

编辑:19/1/2017

@Sean评论

使用monotonically_increasing_id()而不是从星火1.6和

  • 使用`monotonically_increasing_id`代替Spark 1.6 + (19认同)
  • 请注意,这并不能真正回答问题,因为 OP 要求 0-(N-1) 索引。monotonically_increasing_id 不保证连续的 id。 (4认同)