我找到了類似的問題鏈接,但沒有提供如何解決問題的答案。
我想制作一個 UDF,它會為我從列中提取單詞。因此,我想new_column通過將我的 UDF 應用于old_column
from pyspark.sql.functions import col, regexp_extract
re_string = 'some|words|I|need|to|match'
def regex_extraction(x,re_string):
return regexp_extract(x,re_string,0)
extracting = udf(lambda row: regex_extraction(row,re_string))
df = df.withColumn("new_column", extracting(col('old_column')))
AttributeError:“NoneType”物件沒有屬性“_jvm”
如何修復我的功能?我有很多列,想遍歷列串列并應用我的 UDF。
uj5u.com熱心網友回復:
你不需要UDF。當您無法使用 PySpark 做某事時,需要 UDF,因此您需要一些 python 函式或庫。在您的情況下,您可以擁有一個接受列并回傳列的函式,但就是這樣,不需要 UDF。
from pyspark.sql.functions import regexp_extract
df = spark.createDataFrame([('some match',)], ['old_column'])
re_string = 'some|words|I|need|to|match'
def regex_extraction(x, re_string):
return regexp_extract(x, re_string, 0)
df = df.withColumn("new_column", regex_extraction('old_column', re_string))
df.show()
# ---------- ----------
# |old_column|new_column|
# ---------- ----------
# |some match| some|
# ---------- ----------
通過串列中的列“回圈”可以這樣實作:
from pyspark.sql.functions import regexp_extract
cols = ['col1', 'col2']
df = spark.createDataFrame([('some match', 'match')], cols)
re_string = 'some|words|I|need|to|match'
def regex_extraction(x, re_string):
return regexp_extract(x, re_string, 0)
df = df.select(
'*',
*[regex_extraction(c, re_string).alias(f'new_{c}') for c in cols]
)
df.show()
# ---------- ----- -------- --------
# | col1| col2|new_col1|new_col2|
# ---------- ----- -------- --------
# |some match|match| some| match|
# ---------- ----- -------- --------
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468330.html
標籤:阿帕奇火花 pyspark apache-spark-sql 用户定义函数
