如果找到分隔符,则拆分字符串

2024-04-24 21:07:38 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下数据帧

cols = ['Id', 'col1', 'col2', 'col3']
vals = [('1A','Not his side|:|This side', 'This side', 'Not this either|:|but this'),  
        ('1B','Keep this', 'This one|:|keep this', 'remove|:|keep that')]

dd1 = sqlContext.createDataFrame(vals, cols)

#+---+------------------------+--------------------+--------------------------+
#|Id |col1                    |col2                |col3                      |
#+---+------------------------+--------------------+--------------------------+
#|1A |Not his side|:|This side|This side           |Not this either|:|but this|
#|1B |Keep this               |This one|:|keep this|remove|:|keep that        |
#+---+------------------------+--------------------+--------------------------+

我需要做的是在|:|处拆分字符串并保留第二个单词。但是,如果字符串不包含分隔符(|:|),则得到null, i、 电子邮件:

users1 = [F.split(F.col(x), "\\|:\\|").alias(x) for x in cols]
dd1.select(*users1).show()

#+---------+---------+---------+
#|     col1|     col2|     col3|
#+---------+---------+---------+
#|This side|     null| but this|
#|     null|keep this|keep that|
#+---------+---------+---------+

我想要的结果是:

+---+---------+---------+---------+
|Id |col1     |col2     |col3     |
+---+---------+---------+---------+
|1A |This side|This side|but this |
|1B |Keep this|keep this|keep that|
+---+---------+---------+---------+

Tags: idthatnotthisnullsidecol2col3
3条回答

可以使用whensize内置函数作为

users1 = [F.when(F.size(F.split(F.col(x), "\\|:\\|")) > 1, F.split(F.col(x), "\\|:\\|")[1]).otherwise(F.col(x)).alias(x) for x in cols]
dd1.select(*users1).show()

这应该给你

+ -+    -+    -+    -+
| Id|     col1|     col2|     col3|
+ -+    -+    -+    -+
| 1A|This side|This side| but this|
| 1B|Keep this|keep this|keep that|
+ -+    -+    -+    -+

您可以修改答案,以便只使用split函数一次。你知道吗

我希望答案是有益的,应该是一个很好的提示如何进行。你知道吗

使用whenotherwise并检查字符串是否包含"|:|"。具体做法如下:

cols = ['col1', 'col2', 'col3']

users1 = [F.when(F.col(x).contains("|:|"), F.split(F.col(x), "\\|:\\|")[1]).otherwise(F.col(x)).alias(x) for x in cols]
dd1.select(F.col('Id'), *users1)

这里的cols只包含要拆分的列。最后的select也将包含Id列。你知道吗

您在问题中定义的选择不会产生您提到的结果。我想你忘了从数组中选择元素;)

users1 = [F.split(F.col(x), "\\|:\\|").alias(x) for x in cols]
dd1.select(*users1).show()
+  +          +          +          +
|  Id|                col1|                col2|                col3|
+  +          +          +          +
|[1A]|[Not his side, Th...|         [This side]|[Not this either,...|
|[1B]|         [Keep this]|[This one, keep t...| [remove, keep that]|
+  +          +          +          +

要实现所需的功能,只需选择数组的最后一个元素。您可以使用size函数:

users2 = [F.col(x).getItem(F.size(F.col(x))-1).alias(x) for x in cols]
dd1.select(*users1).select(*users2).show()
+ -+    -+    -+    -+
| Id|     col1|     col2|     col3|
+ -+    -+    -+    -+
| 1A|This side|This side| but this|
| 1B|Keep this|keep this|keep that|
+ -+    -+    -+    -+

相关问题 更多 >