访问 PySpark 中的计数列

Accessing count column in PySpark

code:

mydf = testDF.groupBy(testDF.word).count()
mydf.show()

output:

+-----------+-----+
|       word|count|
+-----------+-----+
|        she| 2208|
|    mothers|   93|
|       poet|   59|
|     moving|   18|
|     active|    6|
|       foot|  169|

我想根据字数降序排列这个数据框。

code:

countDF = mydf.orderBy(mydf.count.desc())
countDF.show()

Error:

AttributeError: 'function' object has no attribute 'desc'

请告诉我哪里出错了。

嗯,点表示法不是访问列的最佳方法。虽然 DataFrame 提供列感知 __getattr__ 你可能会遇到像这样的冲突,其中名称将解析为一个方法(这里 DataFrame.count)所以最好使用括号表示法:

mydf.orderBy(mydf["count"].desc())

col函数:

from pyspark.sql.functions import col

mydf.orderBy(col("count").desc())

引用列。