我正在使用 PySpark。例如,我有一個簡單的 DataFrame ,其中包含"df"1 列"Col1",其中包含大量空格,如下所示:
Col1
" - "
"abc "
" xy"
我想在trim. 在 SQL 中很簡單:
select Col1 from df where trim(Col1) <> "-"
結果
abc
xy
我不想在這里使用 SQL 陳述句,所以我都嘗試了
df.where(trim(df.Col1) <> "-").show()
and
df.filter(df.Col1.trim() <> "-").show()
但是兩者都沒有成功,它說這trim不是 a 的屬性DataFrame,當我閱讀 Document Trim Function is in Function Page,而不是 DataFrame Page 時。我不想使用withColumn,因為我仍然想保留舊列的格式。轉換為 SQL 陳述句查詢也不好,因為在此之后我還有很多 Df 函式要使用。
那么我該如何做這個簡單的條件檢查Spark DataFrame呢?
uj5u.com熱心網友回復:
這是正確的語法:
from pyspark.sql import functions as f
data = [(" - ",), ("abc ",), (" xy",)]
df = spark.sparkContext.parallelize(data).toDF(["value"])
df.where(f.trim(f.col("value")) != "-").show()
輸出:
-----
|value|
-----
| abc |
| xy|
-----
<>運算子用于 SQL 語法,在這種情況下等價于!=
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/512313.html
