如何使用 pyspark 从列表中获取最后一项? [英] How do I get the last item from a list using pyspark?
本文介绍了如何使用 pyspark 从列表中获取最后一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么列 1st_from_end
包含空值:
from pyspark.sql.functions import splitdf = sqlContext.createDataFrame([('a b c d',)], ['s',])df.select(split(df.s, ' ')[0].alias('0th'),split(df.s, ' ')[3].alias('3rd'),split(df.s, ' ')[-1].alias('1st_from_end')).展示()
我认为使用 [-1]
是一种获取列表中最后一项的pythonic方法.为什么它在 pyspark 中不起作用?
解决方案
如果您使用的是 Spark >= 2.4.0,请参阅 jxc 的回答 下面.
在 Spark
2.4.0,dataframes API 不支持 -1
对数组进行索引,但您可以编写自己的 UDF 或使用内置的 size()
函数,例如:
Why does column 1st_from_end
contain null:
from pyspark.sql.functions import split
df = sqlContext.createDataFrame([('a b c d',)], ['s',])
df.select( split(df.s, ' ')[0].alias('0th'),
split(df.s, ' ')[3].alias('3rd'),
split(df.s, ' ')[-1].alias('1st_from_end')
).show()
I thought using [-1]
was a pythonic way to get the last item in a list. How come it doesn't work in pyspark?
解决方案
If you're using Spark >= 2.4.0 see jxc's answer below.
In Spark < 2.4.0, dataframes API didn't support -1
indexing on arrays, but you could write your own UDF or use built-in size()
function, for example:
>>> from pyspark.sql.functions import size
>>> splitted = df.select(split(df.s, ' ').alias('arr'))
>>> splitted.select(splitted.arr[size(splitted.arr)-1]).show()
+--------------------+
|arr[(size(arr) - 1)]|
+--------------------+
| d|
+--------------------+
这篇关于如何使用 pyspark 从列表中获取最后一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文