簡體   English   中英

PySpark DataFrame-如何將字符串變量傳遞給df.where()條件

[英]PySpark dataframe - How to pass string variable to df.where() condition

我不確定在pyspark中是否可能。 我相信這應該只是我沒有在這里獲勝:(。

要求:帶入任何FNAME和LNAME為null或0的記錄

預期結果:結果前兩行。

df = sqlContext.read.format('com.databricks.spark.csv').options(header='true').load(fileName)
df.show()

+------+-------+------+
| FNAME|  LNAME|  CITY|
+------+-------+------+
|     0|   null|    NY|
|  null|      0|  null|
|   Joe|   null|    LA|
|  null|   Deon|    SA|
| Steve|   Mark|  null|
+------+-------+------+

colCondition = []
for col in df.columns:
    condition = '(df.'+col+'.isNull() | df.'+col+' == 0)'
    colCondition.append(condition)

dfWhereConditon = ' & '.join(colList)

這是我要實現的目標:

df.where(dfWhereConditon)

這不起作用,因為dfWhereCondition被視為where條件中的字符串。 我該如何解決這個問題,或者有更好的方法來解決這個問題。

謝謝

如果要使用字符串條件,則可以使用SQL filter子句:

condition = ' AND '.join(['('+ col + ' IS NULL OR ' + col + ' = 0)' for col in df.columns])
df.filter(condition)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM