Spark Dataframe 列与其他列的最后一个字符 [英] Spark Dataframe column with last character of other column

查看:43
本文介绍了Spark Dataframe 列与其他列的最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来从数据框列中的字符串中获取最后一个字符并将其放入另一列中.

I'm looking for a way to get the last character from a string in a dataframe column and place it into another column.

我有一个如下所示的 Spark 数据框:

I have a Spark dataframe that looks like this:

    animal
    ======
    cat
    mouse
    snake

我想要这样的东西:

    lastchar
    ========
    t
    e
    e

现在我可以使用如下所示的 UDF 执行此操作:

Right now I can do this with a UDF that looks like:

    def get_last_letter(animal):
        return animal[-1]

    get_last_letter_udf = udf(get_last_letter, StringType())

    df.select(get_last_letter_udf("animal").alias("lastchar")).show()

我主要是想知道是否有更好的方法可以在没有 UDF 的情况下做到这一点.谢谢!

I'm mainly curious if there's a better way to do this without a UDF. Thanks!

推荐答案

只需使用子串函数

from pyspark.sql.functions import substring
df.withColumn("b", substring(col("columnName"), -1, 1))

这篇关于Spark Dataframe 列与其他列的最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆