首页 > 解决方案 > 正则表达式与 pyspark

问题描述

我对pyspark真的很陌生,所以这是一个非常基本的问题:所以我有一个看起来像这样的数据框:

|I  27-May-18 10:1...|false|
|I  27-May-18 10:1...|false|
|I  27-May-18 10:1...|false|
|I  27-May-18 10:1...|false|
|I  27-May-18 10:1...|false|
|W  27-May-18 10:1...|false|
|                 ...|false| ##this one should not be flagged
|W  27-May-18 10:1...|false|

我想将以下所有行连接在一起,如果开头没有 W 或 I 或 E 或 U ,那么它应该看起来像这样:

|I  27-May-18 10:1...|false|
|I  27-May-18 10:1...|false|    
|I  27-May-18 10:1...|false|    
|I  27-May-18 10:1...|false|    
|I  27-May-18 10:1...|false|    
|W  27-May-18 10:1......|false| ##the row after this one was joined to the one before    
|W  27-May-18 10:1...|false|

为此,我认为我标记了行,以某种方式将组分配给行,然后使用 group by 语句。

但是我已经卡在标记行上,因为正则表达式不起作用:

因此,正则表达式将是:'^[EUWI]\s'

当我在 pyspark 中使用它时,它会返回所有错误...

这里的代码:

df_with_x5 = a_7_df.withColumn("x5", a_7_df.line.startswith("[EUWI]\s"))
##I am using start with thats why i can drop the `^`

为什么它不采用我的正则表达式?

标签: pythonregexpyspark

解决方案


if you want to create a flag column, you can try substring:

import pyspark.sql.functions as F

df=df.withColumn('flag', F.substring(df.columnName,1,1).isin(['W', 'I', 'E', 'U'])

it checks the first letter only.

But you can discard creating a new column and directly filter rows:

df=df.filter(F.substring(df.columnName,1,1).isin(['W', 'I', 'E', 'U']==False)

推荐阅读