字符串函数
from pyspark.sql.functions import concat, concat_ws
df = spark.createDataFrame([('abcd','123')], ['s', 'd'])
# 1.直接拼接
df.select(concat(df.s, df.d).alias('s')).show()
# abcd123
# 2.指定拼接符
df.select(concat_ws('-', df.s, df.d).alias('s')).show()
# 'abcd-123'
from pyspark.sql.functions import format_string
df = spark.createDataFrame([(5, "hello")], ['a', 'b'])
df.select(format_string('%d %s', df.a, df.b).alias('v')).show()
# 5 hello
from pyspark.sql.functions import instr
df = spark.createDataFrame([('abcd',)], ['s',])
df.select(instr(df.s, 'b').alias('s')).show()
# 2
from pyspark.sql.functions import substring
df = spark.createDataFrame([('abcd',)], ['s',])
df.select(substring(df.s, 1, 2).alias('s')).show()
from pyspark.sql.functions import regexp_extract
df = spark.createDataFrame([('100-200',)], ['str'])
df.select(regexp_extract('str', '(\d+)-(\d+)', 1).alias('d')).show()
# '100'
df = spark.createDataFrame([('foo',)], ['str'])
df.select(regexp_extract('str', '(\d+)', 1).alias('d')).show()
from pyspark.sql.functions import regexp_replace
df = spark.createDataFrame([('100-200',)], ['str'])
df.select(regexp_replace('str', '(\\d+)', '--').alias('d')).collect()
函数 | 作用 |
---|---|
repeat | 字符串重复 |
split | 分割 |