您可以基于regex以这种方式进行分组。您需要为您的数据编写自己的正则表达式,并且可以按以下方式进行分组。
下面是一种使用一些示例数据进行分组的方法。
假设您的数据帧id
df
数据如下所示。
df.show()
+----+----------+------------+-----------+
|data| itemType| itemGroup| itemClass|
+----+----------+------------+-----------+
| 1|type1_dgdf| group1_flkk|class1_gdfg|
| 1|type1_jhgj| group1_fgfd|class1_grtt|
| 1|type1_657g| group1_6gfh|class1_342e|
| 1| type1_qer| group2_wqw|class1_fgfv|
| 2|type2_seds| group2_wqw|class2_fiuy|
| 2| type2_65|group2_wuyuy|class2_232e|
| 2| type2_ffg| group2_wyty|class2_fere|
+----+----------+------------+-----------+
+--------+---------+---------+-----+
|itemType|itemGroup|itemClass|count|
+--------+---------+---------+-----+
| type1| group2| class1| 1|
| type2| group2| class2| 3|
| type1| group1| class1| 3|
+--------+---------+---------+-----+
代码:
import org.apache.spark.sql.functions.regexp_extract
df.groupBy(
regexp_extract(df("itemType"), "(type\\d).*$", 1).alias("itemType"), // here pattern matches for starting with `type` and then any number using `\d` (\\d for windows).. same logic for others as well.
regexp_extract(df("itemGroup"), "(group\\d).*$", 1).alias("itemGroup"),
regexp_extract(df("itemClass"), "(class\\d).*$", 1).alias("itemClass"))
.count().show()