I have a PySpark dataframe with a column containing a StructField of stringtype which has a dynamic length list of lists.
df.schema: StructType(List(StructField(id,StringType,true),StructField(recs,StringType,true)))
|id | recs |
|ABC|[66, [["AB", 10]]]
|XYZ|[66, [["XY", 10], ["YZ", 20]]]
|DEF|[66, [["DE", 10], ["EF", 20], ["FG", 30]]]
I am trying to flatten the lists to something like this
|id | like_id
|ABC|AB|
|XYZ|XY|
|XYZ|YZ|
|DEF|DE|
|DEF|EF|
|DEF|FG|
What did I try:
I tried using array expressions, it threw me an error since the recs is of StringType as expected
I was able to process this using json loads and itertools in pandas, but I need this processing to happen in spark as the dataframe is large ~30 million and the resulting would be 10 times.
df["recs"].apply(
lambda x: [rec_id[0] for rec_id in json.loads(x)[1:][0]]
)
for i, row in df.iterrows():
....