spark sql:如何计算具有多个条件的行

pyspark sql: how to count the row with mutiple conditions

经过一些操作后我得到了这样的数据框;

df_new_1 = df_old.filter(df_old["col1"] >= df_old["col2"])
df_new_2 = df_old.filter(df_old["col1"] < df_old["col2"])

print(df_new_1.count(), df_new_2.count())
>> 10, 15

我可以通过调用 count() 像上面那样单独找到行数。但是我如何使用 pyspark sql row 操作来做到这一点。即按行聚合。我想看到这样的结果;

Row(check1=10, check2=15)

由于您标记了 pyspark-sql,您可以执行以下操作:

df_old.createOrReplaceTempView("df_table")

spark.sql("""

    SELECT sum(int(col1 >= col2)) as check1
    ,      sum(int(col1 < col2)) as check2
    FROM df_table

""").collect()

或使用API函数:

from pyspark.sql.functions import expr

df_old.agg(
    expr("sum(int(col1 >= col2)) as check1"), 
    expr("sum(int(col1 < col2)) as check2")
).collect()