0

The structure of my Dataframe is dynamic and heavily nested. I would like to extract the string value of the fields called text.

df.select(df['back')
DataFrame[back: struct<attrs:struct<version:int>,content:array<struct<content:array<struct<content:array<struct<type:string,content:array<struct<type:string,text:string>>>>,text:string,type:string>>,type:string>>,type:string>]

df.select(df['back').show()
|[[1], [[[[, Vernetzte Komponenten innerhalb eines Netzwerks mit verschiedenen Hardware-Rechnern realisiert Ja., text]], paragraph]], doc]    

df.select(df['back').collect()
Row(back=Row(attrs=Row(version=1), content=[Row(content=[Row(content=None, text='Vernetzte Komponenten innerhalb eines Netzwerks mit verschiedenen Hardware-Rechnern realisiert Ja.', type='text')], type='paragraph')], type='doc'))
0

1 Answer 1

1

Since the dataframe is dynamic, to iterate over a nested column I recommend to use UDF:

import pyspark.sql.functions as f

@f.udf()
def extract_texts(elements):
  texts = []
  
  while len(elements) > 0:
    element = elements.pop(0)
    if 'content' in element and element['content'] is not None:
      elements.extend(element['content'])
      
    if 'text' in element:
      texts.append(element['text'])

  return texts

new_df = (df
          .withColumn('texts', extract_texts('back.content')))

new_df.show()
# +--------------------+--------------------+
# |                back|               texts|
# +--------------------+--------------------+
# |{{1}, [{[{null, V...|[Vernetzte Kompon...|
# +--------------------+--------------------+
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.