如何根据Pyspark中的条件筛选所有数据帧列?

2024-05-19 15:52:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想过滤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)

Tags: truedfagedataschemavarcolnick
1条回答
网友
1楼 · 发布于 2024-05-19 15:52:37

如果列列表大于10,则无法进行筛选;但是您可以根据您的需要,使用&(and)或|(or)链接每列大于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]
    )
)

相关问题 更多 >