My data set looks like this, where I have a comma delimited set of string values in col1 and col2, and col3 is the two columns that have been concatted together.
+===========+========+===========
|col1 |col2 |col3
+===========+========+===========
|a,b,c,d |a,c,d |a,b,c,d,a,c,d
|e,f,g |f,g,h |e,f,g,f,g,h
+===========+========+===========
Basically, what I'm trying to do is grab all the values that are separated by commas in col3 and append another column with each of the values and their counts.
Basically, i'm trying to get this kind of output in col4:
+===========+========+==============+======================
|col1 |col2 |col3 |col4
+===========+========+==============+======================
|a,b,c,d |a,c,d |a,b,c,d,a,c,d |a: 2, b: 1, c: 2, d: 2
|e,f,g |f,g,h |e,f,g,f,g,h |e: 1, f: 2, g: 2, h: 1
+===========+========+==============+======================
I've figured out how to concat the columns together to get to col3, but I'm having a bit of trouble getting to col4. Here's where I've left off and I'm a bit unsure of where to go from here:
from pyspark.sql.functions import concat, countDistinct
df = df.select(concat(df.col1, df.col2).alias('col3'), '*')
df.agg(countDistinct('col3')).show()
+---------------------+ |count(DISTINCT col3)| +---------------------+ | 2| +---------------------+
Question: How I dynamically count the substrings separated by comma in col3 and make a final column that shows the frequency of each substring for all rows in the dataset?