I have a table with 3 columns:
Table A:
+----+----+----------+
|col1|col2|row_number|
+----+----+----------+
| X| 1| 1|
| Y| 0| 2|
| Z| 2| 3|
| A| 1| 4|
| B| 0| 5|
| C| 0| 6|
| D| 2| 7|
| P| 1| 8|
| Q| 2| 9|
+----+----+----------+
I want to concatenate the strings in "col1" by grouping records based on the "col2" values. "col2" has a pattern of 1 followed by any number of 0s, followed by 2. I want to group records that have "col2" start with 1 and end with 2 (The order of the data frame must be maintained - you can use the row_number column for the order)
For example, The first 3 records can be grouped together because "col2" has "1-0-2". The next 4 records can be grouped together because their "col2" values have "1-0-0-2"
The concatenating part can be done using "concat_ws" after I group these records. But any help on how to group these records based on the "1-0s-2" pattern?
Expected output:
+----------+
|output_col|
+----------+
| XYZ|
| ABCD|
| PQ|
+----------+
You can use the following code to create this sample data:
schema = StructType([StructField("col1", StringType())\
,StructField("col2", IntegerType())\
,StructField("row_number", IntegerType())])
data = [['X', 1, 1], ['Y', 0, 2], ['Z', 2, 3], ['A', 1, 4], ['B', 0, 5], ['C', 0, 6], ['D', 2, 7], ['P', 1, 8], ['Q', 2, 9]]
df = spark.createDataFrame(data,schema=schema)
df.show()