如何使用substrin和pyspark一起使用instr

问题描述 投票:0回答:1

我正在尝试同时使用子字符串和instr函数来提取子字符串,但无法这样做。我尝试使用pyspark本机函数和udf,但是由于“列不可迭代”而出现错误。你能帮忙吗

from pyspark.sql.functions import *
from pyspark.sql.functions import UserDefinedFunction
from pyspark.sql.types import *

data = [
{"chargedate":"2019-01-30"},
{"chargedate":"2019-02-28"},
{"chargedate":"2019-03-30"},
{"chargedate":"2019-04-29"}
]
df = spark.createDataFrame(data)
udf = UserDefinedFunction(lambda x : x.find("01",1),IntegerType())
##1st way
##df.withColumn("Chargemonth",substring(df.chargedate,1,instr(col("chargedate"),'01'))).show()
##2nd way with udf
df.withColumn("Chargemonth",substring(df.chargedate,1,udf(col("chargedate")))).show()
python apache-spark pyspark
1个回答
0
投票

[您正在尝试使用需要substring的功能(Column, int, int),但您通过了(Column, int, Column)来说明出现错误的原因:

列不可迭代

正如我在评论中所说,如果您只需要从日期中提取月份,则最好使用内置函数date_format。当可以避免UDF时,请执行此操作。

关于在SQL Server中如何使用substring ( string , 1 , charindex (search expression, string ))的问题,您可以按照以下步骤进行:

df.withColumn("Chargemonth", col("chargedate").substr(lit(1), instr(col("chargedate"), '01'))).show()

使用列功能substr

注: substr将返回出现的第一个索引,也许这不是您想要的。

© www.soinside.com 2019 - 2024. All rights reserved.