PySpark - 按行和列计算不同

您能否建议如何计算以下情况的不同值。

我在 PySpark 中有数据框(列:'Rank'、'Song'、'Artist'、'Year'、'Lyrics'、'Source')。“歌词”列包含字符串值,应按单词划分。

http://img4.mukewang.com/633e9a320001fa4914410550.jpg

我已经计算了“歌词”列中每一行的所有单词数。我还将字符串转换为列表,将结果保存在新列“uniqWords_count”中。不幸的是,我无法弄清楚如何投入和计算不同的价值。


如果它可能有用,这是代码:


billdf = billdf.withColumn('allWords_count', f.size(f.split(f.col('Lyrics'), ' ')))


billdf = billdf.withColumn('uniqWords_count', f.split(f.col('Lyrics'), ' '))

试图应用 countDistinct 函数,但它导致了错误:


billdf = billdf.withColumn('uniqWords_count', f.countDistinct(f.split(f.col('Lyrics'), ' ')))

Py4JJavaError:调用 o3784.withColumn 时出错。:org.apache.spark.sql.AnalysisException:分组表达式序列为空,并且' Song'不是聚合函数。如果您不在乎得到哪个值,则将'(count(DISTINCT split( Lyrics, ' ', -1)) AS uniqWords_count)' 包装在窗口函数中或将 ' ' 包装在 first() (或 first_value)中。;;Song


侃侃尔雅
浏览 119回答 1
1回答

DIEA

Mohammad Murtaza Hashmi提出了一个解决方案。就我而言,它看起来像这样:billdf = billdf.withColumn('uniqWords',f.size(f.array_distinct("uniqWords")))非常感谢您的帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python