我对pyspark很陌生。我有pyspark数据框,其中包含有关特定人从品牌获得消息的次数的信息。它具有三列id
,brand
和count
,如下所示。
| id | brand | Count |
|:---:|:-------:|:-----:|
| 143 | AD-ABC | 3 |
| 314 | AX-DEFG | 8 |
| 381 | AD-ABC | 6 |
| 425 | AD-XYZP | 7 |
| 432 | AD-GAF | 8 |
| 102 | AD-GAF | 1 |
| 331 | AX-ABC | 10 |
| 191 | AD-GAF | 9 |
| 224 | AD-GAF | 6 |
brand列有点复杂,我想从brand列中派生新列brand2
,如下所示(在-后面保留字符)
+-----+---------+-------+--------+
| id | brand | Count | brand2 |
+-----+---------+-------+--------+
| 143 | AD-ABC | 3 | ABC |
| 314 | AX-DEFG | 8 | DEFG |
| 381 | AD-ABC | 6 | ABC |
| 425 | AD-XYZP | 7 | XYZP |
| 432 | AD-GAF | 8 | GAF |
| 102 | AD-GAF | 1 | GAF |
| 331 | AX-ABC | 10 | ABC |
| 191 | AD-GAF | 9 | GAF |
| 224 | AD-GAF | 6 | GAF |
+-----+---------+-------+--------+
我有一个很大的列表,其中包含我要从数据框中过滤出的品牌,如下所示
brand_subset = ['ABC', 'DEF', 'XYZP'] #The list is very large !!
我想要的数据框如下
+-----+---------+-------+--------+
| id | brand | Count | brand2 |
+-----+---------+-------+--------+
| 143 | AD-ABC | 3 | ABC |
| 381 | AD-ABC | 6 | ABC |
| 425 | AD-XYZP | 7 | XYZP |
| 331 | AX-ABC | 10 | ABC |
+-----+---------+-------+--------+
以上仅是示例场景,实际上列表和表都很大。
任何帮助将不胜感激。 (如果考虑数据库的大小来优化解决方案,那将是很好的选择)
答案 0 :(得分:3)
拆分品牌列并获取第二个元素,然后使用isin
检查列表中是否有brand2
:
import pyspark.sql.functions as F
brand_subset = ['ABC', 'DEF', 'XYZP']
(df.withColumn("brand2",F.split("brand","-")[1]).where(F.col("brand2")
.isin(brand_subset))).show()
或:
(df.withColumn("brand2",F.split("brand","-")[1]).filter(F.col("brand2")
.isin(brand_subset)).show()
+---+-------+-----+------+
| id| brand|Count|brand2|
+---+-------+-----+------+
|143| AD-ABC| 3| ABC|
|381| AD-ABC| 6| ABC|
|425|AD-XYZP| 7| XYZP|
|331| AX-ABC| 10| ABC|
+---+-------+-----+------+