簡體   English   中英

如何將所有 dataframe 列過濾到 Pyspark 中的條件?

[英]How to filter all dataframe columns to an condition in Pyspark?

我想將作為列表列的 col_2 過濾到某個條件,代碼寫在 pandas 中,我正在嘗試將其轉換為 Pyspark。

schema = StructType([
StructField( 'vin', StringType(), True),StructField( 'age', IntegerType(), True),StructField( 'var', IntegerType(), True),StructField( 'rim', IntegerType(), True),StructField( 'cap', IntegerType(), True),StructField( 'cur', IntegerType(), True)
  ])

data = [['tom', 10,54,87,23,90], ['nick', 15,63,23,11,65], ['juli', 14,87,9,43,21]]

df=spark.createDataFrame(data,schema)

df.show()
>>>
+----+---+---+---+---+---+
| vin|age|var|rim|cap|cur|
+----+---+---+---+---+---+
| tom| 10| 54| 87| 23| 90|
|nick| 15| 63| 23| 11| 65|
|juli| 14| 87|  9| 43| 21|
+----+---+---+---+---+---+

col_2=['age','var','rim']

df=df.select(*col_2)
df.show()
>>>
+---+---+---+
|age|var|rim|
+---+---+---+
| 10| 54| 87|
| 15| 63| 23|
| 14| 87|  9|
+---+---+---+

df=df.filter(F.col(*col_2) >=10)

您不能在列列表大於 10 的條件下進行過濾; 但是您可以使用& (and) 或|鏈接每列大於 10 的條件列表。 (或),取決於您的需要。

from functools import reduce

col_2 = ['age','var','rim']
df2 = df.filter(
    reduce(
        lambda x, y: x | y,    # `|` means `or`; use `&` if you want `and`
        [(F.col(c) >= 10) for c in col_2]
    )
)

暫無
暫無

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

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