PySpark:获取字符串中每个单词的第一个字符

PySpark: Get first character of each word in string

对于一项作业,我被要求将客户的姓名缩短为每个姓名的首字母,并用 space 字符分隔。

我在 Python 中找到了很多解决方案,但我无法将其转换为数据框。

DF 看起来像这样:

| ID       | Name           | 
| -------- | -------------- |
| 1        | John Doe       |
| 2        | Roy Lee Winters|
| 3        | Mary-Kate Baron|

我想要的输出是:

| ID | Name | Shortened_name| 
| -------- | -------- | -------------- |
| 1 | John Doe | JD |
| 2 | Roy Lee Winters | RLW |
| 3 | Mary-Kate Baron | MB |

我用下面的代码得到了一些结果,但是当有超过 2 个名字时这不起作用。我还想要更多 'flexible' 代码,因为有些人有 4 或 5 个名字,而其他人只有 1 个。

df.withColumn("col1", F.substring(F.split(F.col("Name"), " ").getItem(0), 1, 1))\
  .withColumn("col2", F.substring(F.split(F.col("Name"), " ").getItem(1), 1, 1))\
  .withColumn('Shortened_name', F.concat('col1', 'col2'))

您可以拆分 Name 列,然后对结果数组使用 transform 函数来获取每个元素的第一个字母:

from pyspark.sql import functions as F

df = spark.createDataFrame([(1, "John Doe"), (2, "Roy Lee Winters"), (3, "Mary-Kate Baron")], ["ID", "Name"])

df1 = df.withColumn(
    "Shortened_name",
    F.array_join(F.expr("transform(split(Name, ' '), x -> left(x, 1))"), "")
)

df1.show()
# +---+---------------+--------------+
# | ID|           Name|Shortened_name|
# +---+---------------+--------------+
# |  1|       John Doe|            JD|
# |  2|Roy Lee Winters|           RLW|
# |  3|Mary-Kate Baron|            MB|
# +---+---------------+--------------+

或使用aggregate函数:

df1 = df.withColumn(
    "Shortened_name",
    F.expr("aggregate(split(Name, ' '), '', (acc, x) -> acc || left(x, 1))")
)