[英]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.