[英]pyspark count number of underscores in each row of a given column
我正在使用pyspark版本1.5.2。 我有一個帶有列“ id”的pyspark 數據框,如下所示:
id
------------
000001_128
000123_1_3
006745_8
000000_9_7
我想計算DF每行中的'_'(下划線)的數量,並執行when操作,以便如果字符串中只有1個下划線,我想將'_1'添加為后綴,否則保留該值照原樣。 因此,理想的結果將是:
id | new_id
------------------------
000001_128 | 000001_128_1
000123_1_3 | 000123_1_3
006745_8 | 006745_8_1
000000_9_7 | 000000_9_7
我正在將pyspark.sql.functions用於其他操作。
任何幫助表示贊賞!
from pyspark.sql.functions import udf
@udf(returnType='string')
def fmt(s):
return s if s.count('_')!=1 else f'{s}_1'
df.withColumn('id', fmt(df.id))
這是一種非udf方法:
您可以使用與該答案相同的方法來計算每個id
的_
數,並使用pyspark.sql.functions.when()
檢查計數是否等於1。如果是,請使用pyspark.sql.functions.format_string()
來創建new_id
,否則使該列保持不變:
import pyspark.sql.functions as f
df.withColumn(
"new_id",
f.when(
(f.size(f.split("id", "_"))-1) == 1,
f.format_string("%s_1",f.col("id"))
).otherwise(f.col("id"))
).show()
#+----------+------------+
#| id| new_id|
#+----------+------------+
#|000001_128|000001_128_1|
#|000123_1_3| 000123_1_3|
#| 006745_8| 006745_8_1|
#|000000_9_7| 000000_9_7|
#+----------+------------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.