我正在使用pyspark创建一个数据框,如下所示:

+----+------+
|   k|     v|
+----+------+
|key1|value1|
|key1|value1|
|key1|value1|
|key2|value1|
|key2|value1|
|key2|value1|
+----+------+

我想使用“withColumn”方法添加一个“rowNum”列,数据帧的结果如下所示:
+----+------+------+
|   k|     v|rowNum|
+----+------+------+
|key1|value1|     1|
|key1|value1|     2|
|key1|value1|     3|
|key2|value1|     4|
|key2|value1|     5|
|key2|value1|     6|
+----+------+------+

rowNum的范围是1到n,n等于原始数。我修改了我的代码,如下所示:
from pyspark.sql.window import Window
from pyspark.sql import functions as F
w = Window().partitionBy("v").orderBy('k')
my_df= my_df.withColumn("rowNum", F.rowNumber().over(w))

但是,我收到错误消息:
'module' object has no attribute 'rowNumber'

我用row_number替换了rowNumber()方法,上面的代码可以运行。但是,当我运行代码时:
my_df.show()

我又收到错误消息:
Py4JJavaError: An error occurred while calling o898.showString.
: java.lang.UnsupportedOperationException: Cannot evaluate expression: row_number()
    at org.apache.spark.sql.catalyst.expressions.Unevaluable$class.doGenCode(Expression.scala:224)
    at org.apache.spark.sql.catalyst.expressions.aggregate.DeclarativeAggregate.doGenCode(interfaces.scala:342)
    at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:104)
    at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:101)
    at scala.Option.getOrElse(Option.scala:121)

最佳答案

Spark 2.2中的解决方案:

from pyspark.sql.functions import row_number,lit
from pyspark.sql.window import Window
w = Window().orderBy(lit('A'))
df = df.withColumn("rowNum", row_number().over(w))

关于pyspark - 在数据框中添加一列,包括从1到n的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42690565/

10-14 19:06
查看更多