我有一个pyspark数据帧,其中有一列正试图从中提取信息。举个例子,该列是4个外键的组合,看起来像这样:
示例1:12345-123-12345-4
示例2:5678-4321-123-12
我试图提取字符串的最后一段,在这种情况下是4&12.你知道我该怎么做吗?
我试过以下几种:
df.withColumn("result", sf.split(sf.col("column_to_split"), '_')[1])
.withColumn("result", sf.col("result").cast('integer'))
但是,两位数值的结果为null,并且它只返回一个用于个位数(0-9(的整数
谢谢!
对于spark2.4,您应该在split
之后在array
上使用element_at
-1
from pyspark.sql import functions as sf
df.withColumn("result", sf.element_at(sf.split("column_to_split","-"),-1).cast("int")).show()
+-----------------+------+
| column_to_split|result|
+-----------------+------+
|12345-123-12345-4| 4|
| 5678-4321-123-12| 12|
+-----------------+------+
Mohammad的回答非常干净,是一个不错的解决方案。但是,如果您需要针对Spark版本<2.4,您可以使用反向字符串功能,取第一个元素,将其反向并转换为整数,例如:
import pandas as pd
import pyspark.sql.functions as f
import pyspark.sql.types as t
df = pd.DataFrame()
df['column_to_split'] = ["12345-123-12345-4", "5678-4321-123-12"]
df = spark.createDataFrame(df)
df.withColumn("result",
f.reverse(f.split(f.reverse("column_to_split"), "-")[0]).
cast(t.IntegerType())).show(2, False)
+-----------------+------+
|column_to_split |result|
+-----------------+------+
|12345-123-12345-4|4 |
|5678-4321-123-12 |12 |
+-----------------+------+
这是如何获得上面序列号的最后几位:
serial_no = '12345-123-12345-4'
last_digit = serial_no.split('-')[-1]
print(last_digit)
所以在你的情况下,试试:
df.withColumn("result", int(sf.col("column_to_split").split('-')[-1]))
如果不起作用,请分享结果。
添加其他方法:
您还可以使用.regexp_extract()
(或(.substring_index()
功能:
Example:
df.show()
#+-----------------+
#| column_to_split|
#+-----------------+
#|12345-123-12345-4|
#| 5678-4321-123-12|
#+-----------------+
df.withColumn("result",regexp_extract(col("column_to_split"),"([^-]+$)",1).cast("int")).
withColumn("result1",substring_index(col("column_to_split"),"-",-1).cast("int")).
show()
#+-----------------+------+-------+
#| column_to_split|result|result1|
#+-----------------+------+-------+
#|12345-123-12345-4| 4| 4|
#| 5678-4321-123-12| 12| 12|
#+-----------------+------+-------+