Оболочка: Azure Databricks Кластер: 11,3 LTS (включая Apache Spark 3.3.0, Scala 2.12)
У меня есть pandas_udf, он работает для 4 строк, но я пробовал с более чем 4 строками, получая ошибку ниже.
PythonException: 'RuntimeError: длина вывода в Scalar iterator pandas UDF должна совпадать с длиной ввода; однако длина вывода была 1, а длина ввода 2.'.
Пожалуйста, найдите ниже код
data =[{"inputData":"<html>Tanuj is older than Eina. Chetan is older than Tanuj. Eina is older than Chetan. If the first 2 statements are true, the 3rd statement is"},{"inputData":"<html>Pens cost more than pencils. Pens cost less than eraser. Erasers cost more than pencils and pens. If the first two statements are true, the third statement is"},{"inputData":"<html>If we have a tree of n nodes, how many edges will it have?"}, {"inputData":"<div>Which of the following data structures can handle updates and queries in log(n) time on an array?"}]
df = spark.createDataFrame(data)
# removing HTML tags from the input text
@pandas_udf(StringType())
def clean_html(raw_htmls: Iterator[pd.Series]) -> Iterator[pd.Series]:
pd.set_option('display.max_colwidth', 10000)
for raw_html in raw_htmls:
cleanr_regx = re.compile("<.*?>|&([a-z0-9]+|#0-9{1,6}|#x[0-9a-f]{1,6});")
cleantext = re.sub(cleanr_regx, " ", raw_html.to_string(index=False))
cleantext = re.sub(" +", " ", cleantext)
yield pd.Series(cleantext)
df = df.withColumn("Question",clean_html("inputData"))
display(df)
Он работает нормально. Но если я добавлю еще одну строку к данным, получаю вышеупомянутую ошибку.
data =[{"inputData":"<div>Look at this series: 36, 34, 30, 28, 24, … What number should come next?"},{"inputData":"<html>Tanuj is older than Eina. Chetan is older than Tanuj. Eina is older than Chetan. If the first 2 statements are true, the 3rd statement is"},{"inputData":"<html>Pens cost more than pencils. Pens cost less than eraser. Erasers cost more than pencils and pens. If the first two statements are true, the third statement is"},{"inputData":"<html>If we have a tree of n nodes, how many edges will it have?"}, {"inputData":"<div>Which of the following data structures can handle updates and queries in log(n) time on an array?"}]
В моем проекте я читаю данные из файла json, также есть такая же проблема, если его 1 строка работает, но более 1 я получаю то же самое,
Кто-нибудь, пожалуйста, помогите мне, я застрял на неделю с той же ошибкой.
Привет @SaideepArikontham, спасибо, все работает. Но у меня такие же ошибки генерируются в других функциях pandas_udf. Можете ли вы объяснить или исправить меня, что я делаю неправильно
Привет @Ancilpa, я не уверен, почему возникает ошибка. В официальной документации также не так много подробностей о pandas udf learn.microsoft.com/en-us/azure/databricks/udf/…
Привет @SaideepArikontham, хорошо, спасибо за поддержку. Я делаю 60 строк логики кода в pndas_udf для строки. Работает для 1 строки, но выше ошибки появляется более одной строки.
По мере увеличения размера данных длина ввода меняется с 1 на другие значения, но длина вывода остается прежней, т. Е. 1. Не уверен, в чем причина.
Вы можете выполнить то же требование, используя следующий код, используя функцию regex_replace
.
from pyspark.sql.functions import regexp_replace
final = df.select("inputData", regexp_replace("inputData", "<.*?>|&([a-z0-9]+|#0-9{1,6}|#x[0-9a-f]{1,6});", "").alias('Question'))
display(final)
from pyspark.sql.functions import lit
from pyspark.sql.window import Window
from pyspark.sql.functions import row_number
demo = df.withColumn('tp',lit(1))
#demo.show()
demo = demo.withColumn("rn", row_number().over(Window.partitionBy("tp").orderBy("tp")))
#demo.show()
dfs = []
for i in range(1,df.count()+1):
if (i==1):
final = demo.filter(demo['rn']==i).withColumn("Question",clean_html(col('inputData')))
elif (i>1):
#print(i)
final = final.union(demo.filter(demo['rn']==i).withColumn("Question",clean_html(col('inputData'))))
final.show(100)
Спасибо @SaideepArikontham, если мы используем цикл, я думаю, что это последовательная обработка. В моем случае мне нужна параллельная обработка для уменьшения временной сложности.
Эй, @AncilPa, это правда. Я дал эту работу только для того, чтобы вы могли использовать существующую UDF pandas без вышеуказанной ошибки. Обновит ответ, если причина ошибки будет установлена.
Почему бы не использовать
regex_replace
вместо этого?final = df.select("inputData", regexp_replace("inputData", "<.*?>|&([a-z0-9]+|#0-9{1,6}|#x[0-9a-f]{1,6});", "").alias('Question'))
этот код генерирует вывод точно в соответствии с вашими требованиями