如果滿足這兩個條件,我需要中斷程式并拋出下面的例外,否則讓程式繼續。這在僅使用第一個條件時作業正常,但在使用這兩個條件時會產生錯誤。如果 DF 非零且 DF.col1 的值不是“字串”,則以下代碼應引發例外。有什么技巧可以讓它作業嗎?
if (DF.count() > 0) & (DF.col1 != 'string'):
raise Exception("!!!COUNT IS NON-ZERO, SO ADJUSTMENT IS NEEDED!!!")
else:
pass
這會引發錯誤:
" Py4JError: An error occurred while calling o678.and. Trace:
py4j.Py4JException: Method and([class java.lang.Integer]) does not exist "
一些樣本資料:
from pyspark.sql.types import StructType,StructField, StringType, IntegerType
data2 = [("not_string","test")]
schema = StructType([ \
StructField("col1",StringType(),True), \
StructField("col2",StringType(),True) \
])
DF = spark.createDataFrame(data=data2,schema=schema)
DF.printSchema()
DF.show(truncate=False)
uj5u.com熱心網友回復:
col1如果資料框中的任何行的值不等于“字串”,IIUC 您想引發例外。
您可以通過使用過濾器和計數來做到這一點。如果有任何行不等于值“字串”,則計數將大于 0,這將評估為True引發您的例外。
data2 = [("not_string","test")]
schema = StructType([ \
StructField("col1",StringType(),True), \
StructField("col2",StringType(),True) \
])
DF = spark.createDataFrame(data=data2,schema=schema)
if DF.filter(DF.col1 != 'string').count():
raise Exception("!!!COUNT IS NON-ZERO, SO ADJUSTMENT IS NEEDED!!!")
Exception: !!!COUNT IS NON-ZERO, SO ADJUSTMENT IS NEEDED!!!
uj5u.com熱心網友回復:
在 Python 中,&運算子是按位運算子,作用于位以執行逐位運算。對于條件中的“和”邏輯,您必須使用and:
if (DF.count() > 0) and (DF.col1 != 'string'):
raise Exception("!!!COUNT IS NON-ZERO, SO ADJUSTMENT IS NEEDED!!!")
else:
pass
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444421.html
